Docker Series Part 2: Building Your First Docker Image

Table of Contents

Docker Series Part 2: Building Your First Docker Image

In the previous part, you learned what Docker is and how to run your first container. Now, let’s take the next step: building your own Docker image!

What is a Docker Image?

A Docker image is a blueprint for your containers. It contains everything your application needs to run: code, dependencies, environment variables, and more.

The Dockerfile

A Dockerfile is a simple text file with instructions for building a Docker image. Here’s a basic example for a Python Flask app:

# Use an official Python runtime as a parent image (Alpine variant for a smaller image)
FROM python:3.11-alpine

# Set the working directory
WORKDIR /app

# Copy requirements and install dependencies
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of your app's source code
COPY . .

# Expose the app port
EXPOSE 5000

# Run the app
CMD ["python", "app.py"]

Your requirements.txt should contain:

flask

And a minimal app.py could look like:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello from Flask in Docker!"

if __name__ == "__main__":
    app.run(host="0.0.0.0")

Building Your Image

  1. Place your Dockerfile, requirements.txt, and app.py in your project directory.
  2. Open a terminal in that directory.
  3. Build your image with:
    docker build -t my-flask-app .
    

Running Your Custom Container

Start a container from your new image:

docker run -p 5000:5000 my-flask-app

Now your Flask app is running in a container, accessible on port 5000!

Recap

  • Docker images are blueprints for containers.
  • You define images with a Dockerfile.
  • Build and run your own images to package and deploy your apps easily.

In the next part, we’ll explore managing multiple containers with Docker Compose. Stay tuned!