Docker Containers: A Practical Getting Started Guide
Docker has revolutionized how we build, ship, and run applications. This practical guide will get you started with Docker containers and help you understand why they're essential for modern development.
What is Docker?
Docker is a platform for developing, shipping, and running applications in containers. Containers are lightweight, standalone packages that include everything needed to run an application.
Containers vs Virtual Machines
| Aspect | Containers | Virtual Machines |
|---|---|---|
| Size | Megabytes | Gigabytes |
| Startup | Seconds | Minutes |
| Isolation | Process-level | Full OS |
| Performance | Near-native | Overhead |
Key Docker Concepts
- Image: A read-only template with instructions for creating a container
- Container: A runnable instance of an image
- Dockerfile: A text file with instructions to build an image
- Registry: A repository for Docker images (like Docker Hub)
Getting Started
Installation
Download and install Docker Desktop from docker.com.
# Verify installation
docker --version
docker run hello-world
Your First Dockerfile
Create a Dockerfile for a Node.js application:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
Basic Commands
# Build an image
docker build -t myapp:1.0 .
# Run a container
docker run -p 3000:3000 myapp:1.0
# List running containers
docker ps
# Stop a container
docker stop <container_id>
# Remove a container
docker rm <container_id>
Docker Compose
For multi-container applications, use Docker Compose:
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000"
depends_on:
- db
db:
image: postgres:14
environment:
POSTGRES_PASSWORD: secret
Run with:
docker-compose up -d
Best Practices
- Use official base images: They're maintained and secure
- Keep images small: Use Alpine-based images when possible
- Use .dockerignore: Exclude unnecessary files
- Don't run as root: Use a non-root user in containers
- Layer caching: Order Dockerfile commands for optimal caching
Conclusion
Docker containers provide a consistent environment from development to production. Master these basics, and you'll be well-equipped to containerize any application.
