A Dockerfile is a file containing instructions to build a Docker image.
A docker image is a self-contained immutable package that typically contains everything required to run an application, including its library dependencies and the application source code or compiled binary. A Dockerfile is a reproducible recipe to built that image.
From the documentation:
Docker can build images automatically by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Using docker build users can create an automated build that executes several command-line instructions in succession.
Use this tag for questions about the Dockerfile syntax or semantics. This is a core part of docker and it will usually be correct to use this tag on Dockerfile questions as well.
Key Links
All links to official documentation on https://docs.docker.com/
:
- Dockerfile reference, describing the Dockerfile syntax
docker build
CLI documentation- Docker Compose
build:
stable (version 3) reference; Compose file build reference ("Compose specification" version) - Best practices for writing Dockerfiles
- Multi-stage builds
- Docker samples, which typically include a language-specific framework
Example
This is a typical example Python application. The final application image is built on the Docker Hub python
image but includes the library dependencies and the actual application code.
# Name the base image to be used for this image.
FROM python:3.11
# Install the application in its own directory. Does not need
# to be an FHS standard directory. Creates the directory if
# required.
WORKDIR /app
# Install the library dependencies. Doing this first in a separate
# step makes rebuilds more efficient.
COPY requirements.txt ./
RUN pip install -r requirements.txt
# Copy the rest of the application code in. (A compiled language
# would need to actually build it here.)
COPY ./ ./
# Document the port the application uses. No practical effects
# beyond documentation, but considered good practice.
EXPOSE 8000
# The default command to use to run the main container process.
CMD ["./app.py"]
To create a Docker image from this Dockerfile, I issue this command within the same directory that contains it:
docker build --tag myapp .
Now I execute the application by running:
docker run -d -p 8000:8000 myapp
This launches the container in the background, running the image's CMD
as the main container process. Host port 8000 is forwarded to container port 8000.
Note that this docker run
invocation makes no reference to the host system. If one were to docker push
the built image to a registry and docker run
it on a remote host, since the entire application is included in the image, they can run it without separately downloading the code or Python runtime on to the host system.