在部署一个网站的时候,可能需要更改Nginx的配置,然后重启Nginx服务,部署的网站才能够访问。
在这里先简单总结一下nginx部署网站的步骤吧。
nginx建站流程简介
server{
listen port1; #你的网站程序里使用的端口号
server_name nginx所在服务器的ip;
location / {
# Pass the request to Gunicorn
proxy_pass http://127.0.0.1:port2; #网站端口号
proxy_read_timeout 6000;
proxy_set_header Host $host: port1;
proxy_set_header X-Real-IP $remote_addr; #你的网站程序里使用的端口号
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
ln -s /etc/nginx/sites-available/homepage.com /etc/nginx/sites-enabled/homepage.com
iptables -I INPUT -p tcp --dport port2 -j ACCEPT
nohup python -m my_server &
systemctl restart nginx
至此,理论上你的网站已经搭建好了,可以访问了。但是你可能会遇到一些问题,
下面就是本文的重点:
1、重启nginx失败,你可能会得到下面一条错误信息:
Job for nginx.service failed because the control process exited with error code. Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journal
那么你可以按照提示去看看到底是什么错误。
但根据我的经验,启动失败很大概率原因是配置文件有问题。
重点来了,你还可以通过这条命令去校验你的Nginx配置是否成功:
nginx -t
如果成功,他会给出如下信息:
# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
如果你的配置文件有问题,也能从错误信息中看出来:
a duplicate default server for [::]:80 in /etc/nginx/nginx.conf:41
错误已经很明显了,有多个配置文件里面使用了80端口。所以你可以用下面这条命令去查找一下:
grep -R default_server /etc/nginx
# 啰嗦一句,-R的意思是递归查找。这条命令会从 /etc/nginx下递归查找所有包含 default_server 的文件
找到该文件,写个别的端口或者删掉没用的文件,这个错误就可以解决了!
2、查看Nginx服务状态你可以发现:
# systemctl status nginx.service
● nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since 2018-11-06 12:31:21 JST; 15s ago
...
11月 06 12:31:20 zhangch-101 nginx[1863]: nginx: [emerg] bind() to 0.0.0.0:5001 failed (98: Address already in use)
11月 06 12:31:21 zhangch-101 systemd[1]: nginx.service: control process exited, code=exited status=1
11月 06 12:31:21 zhangch-101 nginx[1863]: nginx: [emerg] still could not bind()
11月 06 12:31:21 zhangch-101 systemd[1]: Failed to start The nginx HTTP and reverse proxy server.
11月 06 12:31:21 zhangch-101 systemd[1]: Unit nginx.service entered failed state.
11月 06 12:31:21 zhangch-101 systemd[1]: nginx.service failed.
这个错误比较明显,已经有进程占用这个端口了。
这时你就应该去看看哪个进程占用了这个端口:
netstat -nap | grep 5001
但是根据我的经验,应该是你的网站配置文件把你的网站的本地端口和nginx端口写反了。
也就是说把上面的nginx建站流程中第2步的port1,port2换一下,重启服务,这个问题应该就解决了。
3、没有sites-available文件
自己在/etc/nginx/下创建一下就行。
但是别忘了在/etc/nginx/nginx.conf中找到http {}
,在里面加上一句:
include /etc/nginx/sites-enabled/*;