Docker Day 2 Explained: A Beginner's Guide

It's day two of my Docker journey, and I successfully containerized a Flask web application! The goal was to build a simple app with two routes and run it inside a Docker container. Here's a breakdown of what I did and the key lessons I learned along the way.

The Setup: My Flask Application 🧪

I started by creating a basic Flask application. It has two simple routes:

  • /info: A page to display some general information.

  • /login: A mock login page.

To manage the app's dependencies, I created a requirements.txt file with just Flask. This is a best practice that keeps the Dockerfile clean and makes dependency management straightforward.

Dockerizing the Application 📝

The core of this exercise was creating the Dockerfile. I wrote a clean and efficient file to define the container image. Here's what that looked like:

# Use a lightweight official Python image as the base
FROM python:3.9-slim

# Set the working directory inside the container
WORKDIR /app

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

# Copy the rest of the application code
COPY . .

# Expose the default Flask port
EXPOSE 5000

# Set the command to run the application
CMD ["flask", "run", "--host=0.0.0.0"]

I also made sure to create a .dockerignore file. This is an important step to prevent unnecessary files like the Dockerfile itself or .git folders from being copied into the container, which helps keep the image size small.

Key Takeaways & Lessons Learned 💡

This process was a great learning experience. Here are a few key points that stood out:

  1. Flask's Default Port: By default, Flask runs on port 5000. It's crucial to expose this port in the Dockerfile using the EXPOSE instruction.

  2. Container vs. Host: The most significant challenge I faced was accessing the app from my browser. My first attempt failed because I forgot a fundamental concept: the app was running inside the container's isolated network, not on my local machine.

  3. The Fix: Port Mapping! The solution was to use port mapping with the -p flag when running the container. The command docker run -p 5000:5000 my-flask-app maps the container's port 5000 to my host machine's port 5000, allowing me to access the app at http://localhost:5000.


Why This Matters for DevOps 🌐

This exercise really highlights the power of containerization. I now have a self-contained application that can run anywhere Docker is installed, without needing to worry about installing Python or Flask on the host machine. This is a core principle of DevOps—ensuring consistency across different environments and simplifying deployment.

0
Subscribe to my newsletter

Read articles from Manoranjan Sethi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoranjan Sethi
Manoranjan Sethi