Dockerfile Instructions
A Dockerfile has more instructions than FROM, COPY, RUN and CMD. WORKDIR sets the working folder, EXPOSE names a port, ENV sets a variable, and ENTRYPOINT fixes the main command.
Set the working folder
WORKDIR makes /app the folder for the steps after it.
FROM python:3.12-slim
WORKDIR /app
COPY greet.py .
CMD ["python", "greet.py"]Set a variable
ENV sets GREETING inside the image for the program to read.
FROM python:3.12-slim
ENV GREETING="Hello from ENV!"
CMD ["python", "-c", "import os; print(os.environ['GREETING'])"]Example
docker build -t g4-env:1.0 . >/dev/null
docker run --rm g4-env:1.0Key points
- WORKDIR: the folder later steps run in, like cd for the build.
- EXPOSE: the port the app listens on, as a note for the reader.
- ENV: a variable set inside the image for the app to read.
- ENTRYPOINT: the fixed main command. CMD adds its default arguments.
- Use ENTRYPOINT for a fixed program, and CMD for its defaults.
In this example, a Dockerfile sets the GREETING variable with ENV. The container runs a Python one-liner that reads the variable and prints it. The printed greeting proves ENV reached the running container.
Note
EXPOSE does not publish the port. The -p flag on docker run publishes it.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Rust Playground
Exercise
What is the difference between ENTRYPOINT and CMD?