Docker starts nginx and cannot proxy normally
Recently, I wanted to use nginx to proxy the second-level domain name to a different port, and found that an error would be reported
2023/04/12 08:18:28 [error] 24#24: *8 connect() failed (111: Connection refused) while connecting to upstream, client: 58.34.185.106, server: xxx.xxx.xxx, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:20077/", host: "xxx.xxx.xxx"
My configuration is very simple, which is to proxy to different ports through the domain name
server {
listen 80;
server_name xxx.com;
location / {
proxy_pass http://127.0.0.1:20074;
}
}
server {
listen 80;
server_name xxxx.com;
location / {
proxy_pass http://127.0.0.1:20077;
}
}
In fact, this is because the nginx started by docker is used. The nginx started by docker by default uses bridge模式
the port mapping to the outside, and the access in the container localhost
cannot access the host.
Docker network mode | configuration | illustrate |
---|---|---|
host mode | –net=host | The container and the host share the Network namespace |
bridge mode | –net=bridge | The most commonly used mode (this mode is the default) |
none mode | –net=none | The container has an independent Network namespace, but it does not make any network settings, such as assigning veth pair and bridge connection, configuring IP, etc. |
container mode | –net=container:NAME_or_ID | A container shares a Network namespace with another container. The pod in kubernetes is multiple containers sharing a Network namespace |
We only need to change to host
the mode and share the network of the host machine!
Also, it is not recommended to use the command to start the container. If there are more than one container, it is impossible to find where the directory is mounted by itself. It is recommended to usedocker-compose
version: "3"
services:
web:
container_name: nginx
image: nginx
volumes:
- ./html:/usr/share/nginx/html
- ./conf/nginx.conf:/etc/nginx/nginx.conf
- ./conf.d:/etc/nginx/conf.d
- ./logs:/var/log/nginx
restart: always
network_mode: host
Note ⚠️: After using
host
the mode, do not-p
expose the port anymore. You have already used the local network, and all ports are synchronized with the host. Then port mapping is to map the local machine to the local machine. Take off your pants and fart, it’s unnecessaryIf the port is mapped, it will fail to start!