0
0
NginxHow-ToBeginner · 3 min read

How to Use Nginx with Docker Compose: Simple Setup Guide

To use nginx with docker-compose, define an nginx service in your docker-compose.yml file specifying the image, ports, and volumes for configuration. Then run docker-compose up to start the Nginx container with your settings.
📐

Syntax

The basic syntax for using Nginx with Docker Compose involves defining a service in docker-compose.yml. You specify the image to use (usually nginx), ports to expose, and volumes to mount your custom configuration or website files.

This setup lets Docker run Nginx inside a container, forwarding requests from your machine to the container's web server.

yaml
version: '3.8'
services:
  nginx:
    image: nginx:1.25
    ports:
      - "8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./html:/usr/share/nginx/html:ro
💻

Example

This example shows a simple Docker Compose file running Nginx on port 8080, serving static files from a local html folder and using a custom nginx.conf configuration.

yaml
version: '3.8'
services:
  nginx:
    image: nginx:1.25
    ports:
      - "8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./html:/usr/share/nginx/html:ro
Output
Creating network "default" with the default driver Creating nginx ... done # Access http://localhost:8080 in your browser to see the served content.
⚠️

Common Pitfalls

  • Port conflicts: Make sure the host port (e.g., 8080) is free before running Docker Compose.
  • Volume paths: Use correct relative or absolute paths for your config and content folders.
  • File permissions: Ensure your config and html files are readable by the container.
  • Configuration errors: A wrong nginx.conf can cause Nginx to fail starting.
yaml
version: '3.8'
services:
  nginx:
    image: nginx:1.25
    ports:
      - "80:80"  # This may conflict if host port 80 is in use
    volumes:
      - ./wrong-path/nginx.conf:/etc/nginx/nginx.conf:ro  # Wrong path causes failure

# Corrected version:
version: '3.8'
services:
  nginx:
    image: nginx:1.25
    ports:
      - "8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./html:/usr/share/nginx/html:ro
📊

Quick Reference

Remember these key points when using Nginx with Docker Compose:

  • Use the official nginx image with a specific version tag.
  • Map container port 80 to a free host port like 8080.
  • Mount your nginx.conf and website files as read-only volumes.
  • Check file paths and permissions carefully.
  • Run docker-compose up to start the service.

Key Takeaways

Define an nginx service in docker-compose.yml with image, ports, and volumes.
Map container port 80 to a free host port like 8080 to avoid conflicts.
Mount your nginx.conf and website files as read-only volumes for configuration.
Check file paths and permissions to prevent container startup errors.
Use docker-compose up to launch and test your Nginx container easily.