Docker with Nginx
Learn how to use Nginx inside Docker to serve static websites, proxy requests to backend apps, and configure virtual hosts.
Run Nginx with Docker (Quick Start)
docker run -d --name my-nginx -p 8080:80 nginx:latest
Open http://localhost:8080 — you will see the Nginx welcome page.
Serve a Custom HTML Page
Create an index.html file:
<!DOCTYPE html>
<html>
<head><title>Online Learner</title></head>
<body><h1>Hello from Nginx in Docker!</h1></body>
</html>
Mount the file into the container:
docker run -d --name custom-nginx -p 8080:80 -v $(pwd)/html:/usr/share/nginx/html nginx:latest
Custom Nginx Config File
Create nginx.conf:
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
Mount the config:
docker run -d --name nginx-custom-config -p 8080:80 -v $(pwd)/nginx.conf:/etc/nginx/conf.d/default.conf nginx:latestNginx as Reverse Proxy for PHP App
Create docker-compose.yml:
version: "3.9"
services:
nginx:
image: nginx:latest
ports:
- "8080:80"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf
- .:/var/www/html
php:
image: php:8.2-fpm
volumes:
- .:/var/www/html
Nginx config to proxy to PHP-FPM:
server {
listen 80;
root /var/www/html/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ .php$ {
fastcgi_pass php:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
docker compose up -dBuild a Custom Nginx Image
FROM nginx:latest
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY html/ /usr/share/nginx/html/
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
docker build -t my-nginx-image .
docker run -d -p 8080:80 my-nginx-image
Summary
- Use
docker run -p 8080:80 nginxto quickly start Nginx in a container - Mount your HTML files with
-vto serve custom content - Use Nginx as a reverse proxy to forward requests to PHP-FPM containers
- Use Docker Compose to manage Nginx + PHP as a full stack
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
