Introduction
When I introduced docker before, I said that one of its advantages is that multiple environments can be built on the same server and isolated from each other. I did the actual operation yesterday, and I never expected that there would be so many pitfalls, and it would be more time-consuming than building a server from scratch before. After changing several plans, I finally solved it. I will ignore the sadness in the middle and just talk about the operation method.
Recommended tutorial: nginx tutorial
Architecture
The laradock image already exists in the server, which can run the laravel environment and Other PHP includes nginx, mysql, redis, etc.
My idea is to add another nginx container for reverse proxy. Distribute according to the subdomain name, which can be distributed to laradock or any other container (including wordpress, python, java), etc.
Modify lradock
To be modified There is only one place, which is the port nginx listens on.
1. Enter the laradock directory
2. Modify the .env file and modify the NGINX_HOST_HTTP_PORT value from 80 to 8000
3. Stop nginx, docker-compose stop nginx
4. Reinstall nginx, docker-compose build nginx
5. Start docker-compose up -d nginx
At this time, you cannot access it successfully in the browser. Because nginx no longer listens to port 80.
Add nginx container
Add a new nginx container for reverse proxy. When installing laradock, there is already an image of nginx:alpine, and the container can be generated directly. Of course, you can also pull a new image again. (Alpine version is recommended)
1. Check the nginx image ID, docker iamges
2. Generate a new nixn container, docker run --name proxy_nginx -p 80:80 -d [nginx image id]. You can also add the -v parameter to map the configuration file. My environment has less changes and is not needed.
3. When accessed in the browser at this time, it should be the default page of nginx, indicating that the startup is successful
4. Enter the generated container docker exec -it proxy_nginx sh
5. Install vim, apk add vim
6. Check the host ip, /sbin/ip route| awk '/default/ { print $3 }'
7. Add a new configuration file laradock.conf in the /etc/nginx/conf.d/ directory with the following content
server { listen 80; server_name you_site; location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://[宿主机IP]:8000; } }
1. Exit Container, and then restart docker restart proxy_nginx
2. Open port 8000, refer to here
Conclusion
If you visit at this time, you can proxy to laradock nginx in it. If you want to add other containers in the future, just add new proxy rules in proxy_nginx.
The above is the detailed content of Use nginx to reverse proxy multiple docker containers. For more information, please follow other related articles on the PHP Chinese website!