How to Create a Dockerfile for Nginx: Simple Guide
To create a
Dockerfile for Nginx, start with the official Nginx image using FROM nginx. Then add your custom configuration or content by copying files into the container using COPY. Finally, expose port 80 to allow web traffic.Syntax
A basic Dockerfile for Nginx uses these commands:
FROM nginx: sets the base image to the official Nginx image.COPY <source> <destination>: copies your website files or config into the container.EXPOSE 80: tells Docker to expose port 80 for HTTP traffic.CMD ["nginx", "-g", "daemon off;"]: runs Nginx in the foreground so the container stays alive.
dockerfile
FROM nginx COPY ./html /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
Example
This example Dockerfile creates a simple Nginx container that serves static files from a local html folder.
dockerfile
FROM nginx COPY ./html /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
Output
When you build and run this Dockerfile, Nginx serves your static website on port 80 inside the container. Access it via localhost if you map ports.
Common Pitfalls
Common mistakes when creating a Dockerfile for Nginx include:
- Not copying your website files to the correct Nginx directory (
/usr/share/nginx/html). - Forgetting to expose port 80, so the container port is not accessible.
- Not running Nginx in the foreground, causing the container to exit immediately.
Here is a wrong and right example:
dockerfile
# Wrong: Nginx runs in background, container exits FROM nginx COPY ./html /usr/share/nginx/html EXPOSE 80 CMD ["nginx"] # Right: Nginx runs in foreground, container stays alive FROM nginx COPY ./html /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
Quick Reference
Summary tips for creating a Dockerfile for Nginx:
- Use
FROM nginxto start from the official image. - Copy your website files to
/usr/share/nginx/html. - Expose port 80 to allow HTTP traffic.
- Run Nginx in the foreground with
CMD ["nginx", "-g", "daemon off;"].
Key Takeaways
Start your Dockerfile with the official Nginx image using FROM nginx.
Copy your website files into /usr/share/nginx/html inside the container.
Always expose port 80 to allow web traffic to reach Nginx.
Run Nginx in the foreground with CMD ["nginx", "-g", "daemon off;"] to keep the container running.
Avoid common mistakes like running Nginx in the background or missing file copy paths.