← Back to the chapter · Next detail →
Technical detail · Deployment Models and Virtualization
Read an image recipe from Dockerfile to running container
A worked example to read. The following Dockerfile shows how an image is built and run. It is adapted from an older Docker tutorial; this version uses a current-style Python base rather than the tutorial's obsolete Python 2.7 base. Read it as an example, not as a full production setup.
A Dockerfile is a plain-text recipe for an image -- it names a starting point and a sequence of build steps:
# Use a Python runtime as the parent image
FROM python:slim
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
# Document port 80; publish it with docker run -p
EXPOSE 80
# Define an environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
The file starts with a Python image, sets a work folder, and copies the app into it. It installs the listed packages, documents port 80, and sets a name. The final line says what to run when the container starts. In the original example, the app listens on port 80 and returns a web page.
Common misconception: EXPOSE 80 documents the container port; it does not publish it on the host. In this example, the -p 4000:80 run option supplies that missing step.
Building an image from that Dockerfile and giving it a name, then running a container from it, is two commands:
docker build -t docker-file .
docker run -p 4000:80 docker-file
The first command builds an image named docker-file. The second starts a container from that image. Its port mapping sends traffic from port 4000 on the host to port 80 in the container. Thus a browser on the host uses port 4000. The app must still listen on the container port, and host firewall rules can affect access.