Skillversitas

Docker Nginx

How to run Nginx in Docker.

Docker Nginx

# Run Nginx
docker run -d \
  --name nginx \
  -p 80:80 \
  -p 443:443 \
  -v nginx-data:/usr/share/nginx/html \
  nginx:alpine

docker-compose.yml

version: '3.8'

services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro
      - static-files:/usr/share/nginx/html
    depends_on:
      - api
    networks:
      - frontend

  api:
    build: ./backend
    networks:
      - backend

networks:
  frontend:
  backend:

volumes:
  static-files:

Custom Nginx Config

# nginx.conf
events {
    worker_connections 1024;
}

http {
    upstream api {
        server api:3000;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://api;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }

        location /static {
            alias /usr/share/nginx/html;
        }
    }
}

Use Case: Nginx Application

version: '3.8'

services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro
    depends_on:
      - api
    networks:
      - frontend

  api:
    build: ./backend
    networks:
      - backend

  database:
    image: postgres:15
    networks:
      - backend

networks:
  frontend:
  backend:

Everyday Use Case

Case: A developer needs a reverse proxy.

# Run Nginx
docker run -d --name nginx -p 80:80 nginx:alpine

# Check the logs
docker logs nginx

# Reload the config
docker exec nginx nginx -s reload

Best Practices

  1. Use a custom config: For the right configuration
  2. SSL/TLS: For security
  3. Static files: Mount as a volume
  4. Health check: For monitoring

Conclusion

Nginx in Docker is easy to set up. Use a custom config for a reverse proxy and static files.