2 min read

Docker and Containers

Docker is a platform for developing, shipping, and running applications in containers. A container is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries, and settings.

1. Containers vs. Virtual Machines (VMs)

  • Virtual Machines: Virtualize the hardware. Each VM runs a full Operating System (OS) on top of a Hypervisor. This is heavy (GBs in size) and slow to boot.
  • Containers: Virtualize the Operating System. Containers share the host machine's OS kernel but isolate the application processes. This is lightweight (MBs in size) and starts instantly.

2. Key Concepts

Image

A read-only template with instructions for creating a Docker container. It's like a "snapshot" or a "class" in OOP.

  • Example: node:18-alpine, python:3.9, ubuntu:latest.

Container

A runnable instance of an image. It is the actual running process. It's like an "object" in OOP.

Dockerfile

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

# Example Dockerfile for a Node.js app
FROM node:18
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
CMD ["node", "index.js"]

Registry (Docker Hub)

A repository where images are stored and shared (like GitHub for code).

3. Basic Commands

  • Build an image:
    docker build -t my-app .
  • Run a container:
    docker run -p 3000:3000 my-app

    (Maps port 3000 on host to port 3000 in container)

  • List running containers:
    docker ps
  • Stop a container:
    docker stop <container_id>

4. Docker Compose

Docker Compose is a tool for defining and running multi-container Docker applications. You use a YAML file to configure your application's services.

version: "3.8"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

To start everything:

docker-compose up

programming/microservices-architecture