How to Containerize an Application with Docker: A Step-by-Step Guide

Containerizing an application with Docker packages your code and all its dependencies into a lightweight, portable unit that runs consistently across any environment. This tutorial walks you through the core steps: writing a Dockerfile, building an image, and running a container.

First, create a file named Dockerfile in your project root. This file defines the environment for your app. Start with a base image like python:3.11-slim or node:18-alpine, then copy your source code, install dependencies, and set the command to run your app. Below is a minimal example for a Python Flask app:

Article illustration

1. Write a Dockerfile

  • Choose a base image – Use official images from Docker Hub (e.g., FROM python:3.11-slim).
  • Set the working directoryWORKDIR /app creates a folder inside the container.
  • Copy filesCOPY requirements.txt . then RUN pip install -r requirements.txt.
  • Copy source codeCOPY . ..
  • Define the startup commandCMD ["python", "app.py"].

2. Build the Docker Image

Run docker build -t myapp:latest . in your terminal. The -t flag tags the image with a name (e.g., myapp) and optional version (latest). The dot . tells Docker to use the Dockerfile in the current directory. Building creates a reusable snapshot of your application.

3. Run Your Container

Start a container from your image with docker run -d -p 5000:5000 --name mycontainer myapp:latest. The -d flag runs it in detached mode, -p 5000:5000 maps the container’s port 5000 to your host, and --name gives the container a friendly name. Your app is now live at http://localhost:5000.

4. Manage and Extend with Docker Compose

For applications with multiple services (e.g., web server plus database), use a docker-compose.yml file. Define services, networks, and volumes, then run docker-compose up -d. This simplifies multi-container orchestration.

By following these steps, you can easily containerize any application, ensuring it runs identically on your laptop, a teammate’s machine, or a cloud server. Docker removes the “it works on my machine” problem, making deployment simple and reliable.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *