← Back to Guides
DevOps

Docker Fundamentals for Developers

docker containers devops

Docker has become an essential tool for modern software development. This guide will teach you the fundamentals of Docker and how to use it effectively.

What is Docker?

Docker is a platform for developing, shipping, and running applications in containers. Containers package your application with all its dependencies, ensuring it runs consistently across different environments.

Installing Docker

Visit docker.com and download Docker Desktop for your operating system.

Verify the installation:

docker --version
docker run hello-world

Your First Dockerfile

A Dockerfile defines how to build your container image:

FROM node:18-alpine
 
WORKDIR /app
 
COPY package*.json ./
 
RUN npm install
 
COPY . .
 
EXPOSE 3000
 
CMD ["npm", "start"]

Build and run your image:

docker build -t my-app .
docker run -p 3000:3000 my-app

Docker Compose

Docker Compose helps you manage multi-container applications:

version: '3.8'
 
services:
  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgresql://db:5432/mydb
    depends_on:
      - db
 
  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=mydb
      - POSTGRES_PASSWORD=secret
    volumes:
      - postgres_data:/var/lib/postgresql/data
 
volumes:
  postgres_data:

Start your application:

docker-compose up -d

Essential Docker Commands

Here are the commands you’ll use most often:

docker ps
docker images
docker logs <container-id>
docker exec -it <container-id> sh
docker stop <container-id>
docker rm <container-id>
docker rmi <image-id>
docker system prune

Best Practices

1. Use Multi-Stage Builds

Reduce image size with multi-stage builds:

FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
 
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY package*.json ./
RUN npm install --production
CMD ["node", "dist/index.js"]

2. Use .dockerignore

Exclude unnecessary files:

node_modules
.git
.env
*.md
.DS_Store

3. Don’t Run as Root

Create a non-root user:

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001
USER nodejs

4. Use Health Checks

Add health checks to your Dockerfile:

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD node healthcheck.js

Debugging Containers

View logs:

docker logs -f <container-id>

Access container shell:

docker exec -it <container-id> sh

Inspect container:

docker inspect <container-id>

Conclusion

Docker simplifies application deployment and ensures consistency across environments. Start containerizing your applications today and experience the benefits of modern development workflows.