appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Build your own image

Lesson 2 of 410 minBeginner

Write a Dockerfile and build and tag an image.

A Dockerfile is a recipe: each instruction adds a layer to the image. This one packages a small Python app.

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]
InstructionMeaning
FROMBase image to start from
WORKDIRWorking directory inside the image
COPYCopy files from your folder into the image
RUNRun a command while building
EXPOSEDocuments the port the app uses
CMDDefault command when the container starts

Build and run

docker build -t myapp:1.0 .          # build from the Dockerfile in this folder
docker run -p 8000:8000 myapp:1.0

Cache-friendly order

Docker caches layers. Copy the dependency file and install before copying the rest of the code, so changing your code does not reinstall everything.

.dockerignore

List files to leave out of the build, such as .git, node_modules and .env, to keep images small and avoid leaking secrets.

CarefulDo not put secrets in a Dockerfile or image. Anyone with the image can read every layer. Pass them at run time with environment variables or a secrets manager.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

Hintdocker build with -t and a dot.
2. Which instruction sets the default command of the container?
3. Why copy requirements.txt and install before copying the code?
4. Where should secrets go?

Key terms