Module 3 Lesson 2: Dockerfile Basics
·DevOps

Module 3 Lesson 2: Dockerfile Basics

Master the syntax of the Dockerfile. Learn the core instructions (FROM, RUN, COPY, CMD) needed to turn your source code into a portable Docker image.

Module 3 Lesson 2: Dockerfile Basics

A Dockerfile is a simple text document that contains all the commands a user could call on the command line to assemble an image.

1. The Core Instructions

A typical Dockerfile looks like this:

# 1. Choose a starting point
FROM python:3.9-slim

# 2. Set the working directory inside the container
WORKDIR /app

# 3. Copy files from your computer INTO the container
COPY . .

# 4. Run commands to install things
RUN pip install -r requirements.txt

# 5. Define what happens when the container starts
CMD ["python", "app.py"]

Breakdown:

  • FROM: Every Dockerfile must start with this. It defines the "Base Image."
  • WORKDIR: Like cd. It ensures all following commands happen in that folder.
  • COPY: Takes files from the "Building context" (your laptop) and puts them in the image.
  • RUN: Executes a command during the build process. Use this to install libraries.
  • CMD: Defines the default command that runs only when the container is actually launched.

2. Building the Image

Once you have your Dockerfile saved in a folder with your code, you "Compile" it using the docker build command.

docker build -t my-custom-app:v1 .
  • -t: "Tag" (the name of the image).
  • .: The "Context." It tells Docker: "Look in the current folder for the Dockerfile and the files to copy."

3. RUN vs. CMD (Common Confusion)

  • RUN happens at Build Time. (e.g., "Install Python"). It creates a new layer in the image.
  • CMD happens at Run Time. (e.g., "Start the web server"). It does NOT create a layer. It's just a setting.

4. Best Practice: The .dockerignore file

Just like .gitignore, you don't want to copy everything into your image (like your node_modules or .git folder). Create a file named .dockerignore in the same folder:

node_modules
.git
*.log

Exercise: The Python Build

Scenario: You have a script hello.py that just says "Hello World".

  1. Write a Dockerfile that:
    • Starts from alpine (a tiny Linux).
    • Copies hello.py to /scripts/.
    • Runs the command python3 /scripts/hello.py when it starts.
  2. Research: What happens if you forget to include python3 in your base image?
  3. Command: What is the exact terminal command to build this and name it my-hello:latest?

Summary

The Dockerfile is the "Recipe" for your infrastructure. By mastering just 5 or 6 keywords, you gain the power to automate the entire setup of your development and production environments.

Next Lesson: Why your builds are fast: Layers and caching.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn