docker nginx反向代理 nginx-proxy
编辑于 2023-12-29 16:49:02 阅读 2033
我们知道nginx本身是有 反向代理 功能的,下面介绍的nginx-proxy
是 docker 场景下,不用写传统的反向代理配置,即可实现 反向代理的效果
下面来看一个docker-compose.yml
version: '3'
networks:
web-network:
services:
docker-nginx:
image: nginx:1.21.3
restart: always
environment:
- VIRTUAL_PORT=80
- VIRTUAL_HOST=whoami.local,192.168.10.4,localhost,127.0.0.1,m.cw.net
networks:
- web-network
docker-2048:
image: alexwhen/docker-2048
environment:
- VIRTUAL_PORT=80
- VIRTUAL_HOST=2048.cw.net
networks:
- web-network
nginx-proxy:
image: nginxproxy/nginx-proxy:1.0.0
restart: always
ports:
- 80:80
- 443:443
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
networks:
- web-network
如上docker-nginx
,docker-2048
是两个独立的应用,都使用的80端口,在没有添加nginx配置文件的前提下,两个都可以使用80端口访问,分别是m.cw.net
,2048.cw.net
很明显m.cw.net
,2048.cw.net
域名是假的,修改 hosts
vi /etc/hosts
127.0.0.1 2048.cw.net m.cw.net
使用avahi,无需修改hosts
version: "3.7"
networks:
web-network:
services:
docker-nginx:
image: traefik/whoami:v1.10.1
restart: always
environment:
- VIRTUAL_PORT=80
- VIRTUAL_HOST=whoami.local
networks:
- web-network
docker-2048:
image: traefik/whoami:v1.10.1
environment:
- VIRTUAL_PORT=80
- VIRTUAL_HOST=2048.local
networks:
- web-network
nginx-proxy:
image: nginxproxy/nginx-proxy:1.3.1
restart: always
ports:
- 80:80
- 443:443
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
networks:
- web-network
avahi-helper:
# 这个容器会将以 .local 结尾的 Host 广播出去
# 在局域网的用户就都能访问到了
image: hardillb/nginx-proxy-avahi-helper
restart: unless-stopped
volumes:
- /var/run/docker.sock:/tmp/docker.sock
- /run/dbus/system_bus_socket:/run/dbus/system_bus_socket
networks:
- web-network
高级 - acme-companion
配合 acme-companion
,可以自动给域名生成免费的证书,内部使用的acme.sh
,需要部署到服务器,并且80端口空闲
version: '3'
networks:
web-network:
volumes:
conf:
vhost:
html:
certs:
acme:
services:
docker-nginx:
image: nginx:1.21.3
container_name: nginx
restart: always
environment:
- VIRTUAL_PORT=80
- VIRTUAL_HOST=acme.cw.net
- LETSENCRYPT_HOST=acme.cw.net
- LETSENCRYPT_EMAIL=chudaozhe@outlook.com
networks:
- web-network
nginx-proxy:
image: nginxproxy/nginx-proxy:1.0.0
container_name: nginx-proxy
restart: always
ports:
- 80:80
- 443:443
volumes:
- conf:/etc/nginx/conf.d
- vhost:/etc/nginx/vhost.d
- html:/usr/share/nginx/html
- certs:/etc/nginx/certs:ro
- /var/run/docker.sock:/tmp/docker.sock:ro
networks:
- web-network
acme-companion:
image: nginxproxy/acme-companion:2.2.0
container_name: nginx-proxy-acme
volumes_from:
- nginx-proxy
volumes:
- certs:/etc/nginx/certs:rw
- acme:/etc/acme.sh
- /var/run/docker.sock:/var/run/docker.sock:ro
networks:
- web-network