![Nginx 重定向到 Docker 容器](https://linux22.com/image/1593371/Nginx%20%E9%87%8D%E5%AE%9A%E5%90%91%E5%88%B0%20Docker%20%E5%AE%B9%E5%99%A8.png)
我将个人服务器 SSL 加密,这样外界只能访问端口 443。但是,这样做会锁定我的 Web 应用,使其无法访问外界。
要点是,我有两个 Docker 链,并且<domain>:2019
是<domain>:2020
两个独立的 Web 应用程序,每个应用程序都由 Nginx 容器提供服务,并且在我的本地计算机上正确输出。我希望使用主机的 Nginx 服务<domain>:2019
输出到example1.com
和<domain>:2020
输出到example2.com
。我该怎么做呢?
[编辑]
Docker 链具有各自的 Nginx 容器,如下所示:
nginx:
container_name: domain_nginx
build:
context: ./nginx
volumes:
- static_volume:/usr/src/domain_django/static
ports:
- "2019:80"
depends_on:
- django
Nginx 容器输出到的位置127.0.0.1:2019
。我希望用户example1.com
看到127.0.0.1:2019
答案1
由于您使用的是 docker-compose,因此只需使用容器名称/服务的名称。尝试使用 nginx 将此配置添加到您的容器中:
http {
include /etc/nginx/mime.types;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
server {
listen 80 default_server;
listen [::]:80;
server_name www.example1.com example1.com www.example2.com example2.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name www.example1.com example1.com;
ssl_certificate ssl/fullchain1.pem;
ssl_certificate_key ssl/privkey1.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
keepalive_timeout 70;
location / {
proxy_pass http://<container_name>:2021; ###<-------HERE you can use webapp
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name www.example2.com example2.com;
ssl_certificate ssl/fullchain2.pem;
ssl_certificate_key ssl/privkey2.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
keepalive_timeout 70;
location / {
proxy_pass http://<container_name>:2022; ###<-------HERE you can use webapp
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
旧版 docker-compose 的示例
version: '2'
services:
# webapp is the name that you can use inside the nginx configuration
webapp:
build: build
volumes:
- .:/home/noc/app
ports:
- 8000:8000
environment:
- RECAPTCHA_SECRET_KEY=****
- RECAPTCHA_SITE_KEY=****
- DB_HOST=******
nginx:
image: nginx:1.10.2
volumes:
- ./static:/var/www/static
- ./config/nginx.conf:/etc/nginx/nginx.conf
- /etc/letsencrypt/archive/:/etc/nginx/ssl
links:
- webapp
depends_on:
- webapp
ports:
- 80:80
- 443:443
command: /bin/bash -c "nginx -g 'daemon off;'"
更多信息:Docker 文档