参考:How To Set Up Django with Postgres, Nginx, and Gunicorn on CentOS 7
环境配置
安装组件:
sudo yum install epel-release
sudo yum install postgresql-server postgresql-devel postgresql-contrib gcc nginx
初始化pg库并配置为允许密码验证:
sudo postgresql-setup initdb
sudo vim /var/lib/pgsql/data/pg_hba.conf
修改为:
. . .
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
#host all all 127.0.0.1/32 ident
host all all 127.0.0.1/32 md5
# IPv6 local connections:
#host all all ::1/128 ident
host all all ::1/128 md5
启动服务:
sudo systemctl start postgresql
sudo systemctl enable postgresql
postgresql_35">postgresql配置
centos7中postgresql配置文件位置:
/var/lib/pgsql/data/postgresql.conf
如何修改绑定端口
修改/var/lib/pgsql/data/postgresql.conf
文件中的port:
port = 5431 # (change requires restart)
# Note: In RHEL/Fedora installations, you can't set the port number here;
# adjust it in the service file instead.
发现无效。仔细看注释:在RHEL/Fedora系统中不能在这配置端口,而要去修改service文件,好吧……
service文件位置为:
/usr/lib/systemd/system/postgresql.service
修改端口配置:
# Port number for server to listen on
Environment=PGPORT=5431
systemctl daemon-reload
如何修改监听IP
默认情况下数据库不接受外部访问。
如何让数据库接受来自所有IP的连接?
配置监听IP的话,就可以修改/var/lib/pgsql/data/postgresql.conf
了:
listen_addresses = '*'
Gunicorn服务配置
vim /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=root
Group=root
WorkingDirectory=/home/django-data-assets/
ExecStart=/root/miniconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/home/django-data-assets.sock core.wsgi
[Install]
WantedBy=multi-user.target
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
sudo systemctl restart gunicorn
Nginx配置
vim /etc/nginx/nginx.conf
# Django Server
server {
listen 35888;
server_name 127.0.0.1;
location = /favicon.ico {
root /home/django-data-assets/static;
}
# 注意下面的location后面没有等号=, 否则找static文件就404
location /static/ {
root /home/django-data-assets;
}
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://unix:/home/django-data-assets.sock;
}
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
sudo nginx -t
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl restart nginx
关闭防火墙
firewall-cmd --state
systemctl stop firewalld
systemctl disable firewalld
systemctl mask --now firewalld
清除iptables规则:
iptables -F
遇到过的坑是,已经执行了systemctl stop firewalld,结果firewall-cmd --state还是显示running。
解决办法:重启centos即可。