averainy's Blog

averainy

02 Sep 2022

解决nginx: [emerg] host not found in upstream 'xxx.com'

我用nginx配置了一个反向代理,每次服务器重启之后,nginx都会报:nginx: [emerg] host not found in upstream 'xxx.com'的错误。这个错误的原因其实很简单,就是nginx无法解析xxx.com。解决方法就是以下流程:

  1. 确认xxx.com是否能够被本地的dns解析。
  2. 如果不能解析就在/etc/hosts文件中添加相应的自定义解析
  3. 如果能解析,那就是我碰到的这种情况。问题出在nginx启动时可能dns服务器没启动,或者没有正常解析。我的解决方法是修改nginx.service配置,修改如下:
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/usr/sbin/nginx -s reload
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
PrivateTmp=true
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

增加了Restart=on-failureRestartSec=42s。目的是在启动失败时,等待42秒之后再次重启。 修改完记得执行systemctl daemon-reload