How to make a Docker image

Using a Docker image, you can build a Docker container. Then how can I make the image?

Docker images are from containers

Like each container from an image, a Docker image is also from a container so it is essential to define how a container works on Dockerfile.

FROM baseImage

RUN command

CMD ["executable", "parameter"]

A sample structure of Dockerfile looks like this. First, choose baseImage. A Docker image is consist of many layers and the basement of them is called baseImage. It is similar to a kind of OS in a certain image. Second, run several commands. They contain additional installation, adding layers above the baseImage. (It is called layer caching.) The final line is a start command. You will run a container based on the contructed image and the start command will be executed.

The image below is steps after executing docker build ./.

docker image

Dockerfile check a baseImage first and make a temporary container. The Docker server puts a snapshot and a start command in the container and make a target image. If the image is created, the container is deleted.

Make a Dockerfile to execute a python script

I make a very simple python script file test.py and a Dockerfile to execute it.

FROM python:latest

WORKDIR /usr/src/app

COPY test.py ./

CMD ["python", "test.py"]

There is two new commands: WORKDIR is to set a working directory and COPY is to copy a local file to a container. Setting the working directory first is important because the default position is on root. There is a danger of overwriting and a managing inconvenience while running commands on root. Copying files is also necessary to use local files in a container. Containers cannot reach resources outside of them.

python script

Make a Docker image with docker build ./ and run a container with docker run <IMAGE ID>. There is hello world! at the bottom. Now you can make a Docker image to build your own environment!

Plus, for your convenience, you can give a certain name for the image: docker build -t <username>/<repository>/<project>:<version> ./.

give a name

Like this!

References


💬 Any comments and suggestions will be appreciated.

Leave a comment