Docker for Developers
Docker revolutionizes how we develop, ship, and run applications. Here's everything you need to get started.
Why Docker?
- Consistency - "Works on my machine" becomes "works everywhere"
- Isolation - Each app runs in its own container
- Portability - Deploy the same container anywhere
- Efficiency - Lighter than virtual machines
Basic Concepts
Images vs Containers
- Image: A blueprint (like a class)
- Container: A running instance (like an object)
Your First Dockerfile
# Use Node.js base image
FROM node:18-alpine
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy source code
COPY . .
# Expose port
EXPOSE 3000
# Start the app
CMD ["npm", "start"]
Essential Commands
# Build an image
docker build -t myapp .
# Run a container
docker run -p 3000:3000 myapp
# List running containers
docker ps
# Stop a container
docker stop <container_id>
# View logs
docker logs <container_id>
Docker Compose
Manage multi-container applications:
# docker-compose.yml
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000"
depends_on:
- db
db:
image: postgres:14
environment:
POSTGRES_PASSWORD: secret
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
Run with:
docker-compose up -d
Development Workflow
Use bind mounts for hot reloading:
services:
web:
build: .
volumes:
- .:/app
- /app/node_modules
command: npm run dev
Best Practices
- Use .dockerignore - Exclude node_modules, .git
- Multi-stage builds - Smaller production images
- Non-root user - Security best practice
- Layer caching - Order Dockerfile commands wisely
Conclusion
Docker simplifies development and deployment. Start containerizing your projects today!