Create multiple sites with single nginx server
When we are using local dev web server solutions like XAMPP, MAMP, WAMP or LAMP, we have a greater choice to run multiple websites. But in docker, most of us are struggling to run multiple websites from a single Nginx docker image. It is good idea to have all our testing websites from a single place. This blog describes how to use multiple websites with single Nginx docker image.
Please note that this solution is for your learning purposes. Please do not use this for client projects.
You have to create separate dockers for each client.
Nginx itself can’t run PHP applications, so we have to use PHP-FPM to run the PHP application with Nginx. So here, I am using different images for Nginx and PHP-FPM.
Please download sample code from https://github.com/ishdidev/example_nginx_multisite
In this example, I already added three sites.
http://site1.staging/
http://site2.staging/
http://site3.staging/
If you want to add a new one please do the below steps:
1. Create a folder on root directory Eg: site4
2. On that folder you can add your site files
3. Edit setup/docker-compose.yml file, map new sites config under nginx/volume section
nginx:
image: nginx:1.23.0-alpine
container_name: "ishdidev_nginx"
volumes:
- ./local/nginx/nginx.conf:/etc/nginx/nginx.conf
- ./local/nginx/site1.conf:/etc/nginx/conf.d/default.conf
- ./local/nginx/site2.conf:/etc/nginx/conf.d/site2.conf
- ./local/nginx/site3.conf:/etc/nginx/conf.d/site3.conf
- ./local/nginx/site4.conf:/etc/nginx/conf.d/site4.conf
- ..:/var/www/html:cached
Also add site aliases
networks:
local:
aliases:
- site1.staging
- site2.staging
- site3.staging
- site4.staging
Map new sites folder on PHP container
volumes:
- ../site1:/var/www/html/site1:cached
- ../site2:/var/www/html/site2:cached
- ../site3:/var/www/html/site3:cached
- ../site4:/var/www/html/site4:cached
4. Add site4.conf file on setup/local/nginx folder. This is your nginx configuration file for new site
Please note that, the configuration can change based on the framework you are using. You have to make sure that you are using appropriate configuration to run the respective projects.
Eg: For Drupal you can use https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/
The important part of this file is to use correct server name and root folder for the project.
server_name site4.staging;
root /var/www/html/site4;
The new step is to add new site on your computer host file.
Eg: on Mac, /etc/hosts
127.0.0.1 site4.staging
If everything is okay you can run ‘make project-start’ command from the root folder.
Then open http://site4.staging/ on your browser
Hooray !! Your site is up and running
Thank you.