Building Images

Dockerfile

  • Dockerfile is a simple text file to create a docker image.
  • Default file name is “Dockerfile”

Example dockerfile

ENV
FROM
LABEL maintainer=""
      version=""  
WORKDIR
RUN
VOLUME
EXPOSE
ENTRYPOINT --> Executes custom scripts while starting a docker container
           --> Do not add layer to docker image
CMD
# Example dockerfile
COPY docker-entrypoint.sh /
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]

How to build a docker image

#docker image build -t <image_name>:<version_tag> .
docker image build -t ansible:v1.0 .

How to run the container

docker container run -d -t --name ansible ansible:v1.0 bin/bash

How to connect to a running container

$ docker container exec -it <container_id> bash
# (or) to run shell command directly on a running container, then
$ docker container exec <container_name/id> cat /appl/readme.txt

Data persistance and volume sharing between running containers

In docker, sharing of volumes can be done in 2 ways

  • Add VOLUME in dockerfile , example VOLUME [/appl]
  • [or] Add -v <volume_path> as a flag while running the container to expose the path, example below
docker container run --rm -itd --name <container_name> -v $PWD:/appl -v /appl/data

Inorder to access data from other containers, use volumes-from flag while running the container

docker container run --rm -itd --name <dest-container> --volumes-from <src_container_name_from_which_data_is_accessed>

optimizing docker images

.dockerignore

Useful docker commands

# To stop all running containers in one go, below command can be used
docker container stop $(docker container ls -a -q)

References

Detailed Explanation of Dockerfile
Best practices for writing Dockerfiles

Video References


Last modified July 16, 2024: code refactored (add6d20)