What Are Docker Containers? A Beginner-Friendly Guide

Docker containers are lightweight, portable, and self-contained units that package software and its dependencies into a single, standardized environment. They allow you to run applications consistently across any system, from your laptop to a production server. Here’s everything you need to know:


1. Containers vs. Virtual Machines (VMs)


2. Key Components of Docker Containers


3. Key Features of Docker Containers


4. How Containers Work

  1. Dockerfile → Image:

    • Write a Dockerfile to define dependencies, code, and startup commands.
    • Example:
      FROM python:3.9
      WORKDIR /app
      COPY . .
      RUN pip install -r requirements.txt
      CMD ["python", "app.py"]
      
    • Build the image:
      docker build -t my-python-app .
      
  2. Run the Container:

    docker run -d -p 5000:5000 --name my-app my-python-app
    
    • -d: Run in detached mode (background).
    • -p 5000:5000: Map host port 5000 to container port 5000.
  3. Manage Containers:

    • List running containers: docker ps
    • Stop a container: docker stop my-app
    • Start a stopped container: docker start my-app
    • Access a running container’s shell: docker exec -it my-app bash

5. Use Cases for Docker Containers


6. Quick Start: Run Your First Container

  1. Install Docker:

  2. Run a Sample Container:

    docker run -d -p 80:80 --name my-nginx nginx:latest
    
    • Open http://localhost in your browser to see the NGINX welcome page.
  3. Stop and Remove the Container:

    docker stop my-nginx && docker rm my-nginx
    

7. Common Docker Commands

Command Description
docker run IMAGE Start a new container
docker build -t TAG . Build an image from a Dockerfile
docker ps List running containers
docker exec -it CONTAINER bash Access a container’s shell
docker stop CONTAINER Stop a container
docker logs CONTAINER View container logs
docker pull IMAGE Download an image from a registry

8. Best Practices for Containers


9. Learn More