Nginx in Docker Configuration

Run and configure Nginx inside Docker containers with custom configuration files, SSL certificates, multi-stage builds, and Docker Compose examples.

Setup

Detailed Explanation

Running Nginx in Docker provides consistent deployments across environments, easy horizontal scaling, and process isolation. Whether serving static files or acting as a reverse proxy, containerized Nginx simplifies infrastructure management significantly.

Basic Dockerfile

FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY html/ /usr/share/nginx/html/
EXPOSE 80

The nginx:alpine image is lightweight at roughly 40MB, making it ideal for production containers where image size affects deployment speed and storage costs.

Docker Compose Setup

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
      - ./html:/usr/share/nginx/html:ro
    depends_on:
      - app
  app:
    build: .
    expose:
      - "3000"

Proxying to Other Containers

In Docker Compose, containers on the same network communicate using service names as hostnames. Reference the service name directly in your proxy_pass directive:

upstream app {
    server app:3000;
}

Docker's internal DNS resolver handles the service name resolution automatically, and if you scale the app service, Docker distributes connections across all running instances.

SSL with Docker

Mount your SSL certificates as read-only volumes for security. For automated Let's Encrypt certificate management, use a companion certbot container:

certbot:
    image: certbot/certbot
    volumes:
      - ./ssl:/etc/letsencrypt
    entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h; done'"

Multi-Stage Build for SPAs

Build your frontend application and serve the compiled output with Nginx using a single multi-stage Dockerfile, keeping the final image size minimal:

FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf

Health Checks

Add a Docker health check directive to enable container orchestrators to monitor Nginx availability and restart unhealthy containers automatically:

HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost/ || exit 1

Logging in Docker

The official Nginx Docker image symlinks access and error logs to /dev/stdout and /dev/stderr respectively, integrating seamlessly with Docker's logging drivers for centralized log collection and analysis.

Use Case

You are containerizing your application stack with Docker Compose and need Nginx to serve as the entry point, routing traffic to multiple backend services in separate containers.

Try It — Nginx Config Generator

Open full tool