0
0
NginxHow-ToBeginner · 3 min read

How to Use Nginx with Docker: Simple Guide and Example

To use nginx with docker, you run an Nginx Docker container using the official image with docker run. You can map ports and mount configuration files or website content to customize Nginx inside the container.
📐

Syntax

The basic command to run Nginx in Docker is:

  • docker run: Starts a new container.
  • -d: Runs the container in the background (detached mode).
  • -p <host_port>:<container_port>: Maps a port on your computer to the container's port (Nginx listens on 80 by default).
  • nginx: The official Nginx Docker image name.

You can also mount files or folders with -v to customize Nginx configuration or serve your own website files.

bash
docker run -d -p 8080:80 nginx
💻

Example

This example runs an Nginx container serving a custom HTML page from your local folder.

It mounts your ./html folder to the container's default web root /usr/share/nginx/html and maps port 8080 on your computer to port 80 in the container.

bash
mkdir -p html
echo '<h1>Hello from Nginx in Docker!</h1>' > html/index.html
docker run -d -p 8080:80 -v $(pwd)/html:/usr/share/nginx/html:ro nginx
Output
a container ID string (e.g., 3f2a1b4c5d6e7f8g9h0i1j2k3l4m5n6o7p8q9r0s1t2u3v4w5x6y7z8a9b0c1d2e)
⚠️

Common Pitfalls

  • Not mapping ports correctly: If you forget -p, you cannot access Nginx from your browser.
  • Incorrect volume mount paths: Use absolute paths and ensure the folder exists on your host.
  • File permission issues: Mounting volumes as read-only (:ro) is safer but ensure Nginx can read the files.
  • Running multiple containers on the same port causes conflicts.
bash
docker run -d nginx
# This runs Nginx but you cannot access it because no ports are mapped.

# Correct way:
docker run -d -p 8080:80 nginx
📊

Quick Reference

CommandDescription
docker run -d -p 8080:80 nginxRun Nginx container accessible on localhost:8080
-v /host/path:/container/path:roMount host folder as read-only inside container
docker psList running containers
docker stop Stop a running container
docker logs View container logs

Key Takeaways

Use the official Nginx Docker image with docker run to start a web server quickly.
Map container port 80 to a host port with -p to access Nginx from your browser.
Mount local folders with -v to serve custom content or configuration inside the container.
Always check port mappings and volume paths to avoid common access issues.
Use docker ps and docker logs to manage and debug your Nginx container.