我正在尝试使用Gunicorn和nginx在Amazon EC2实例上提供Flask应用程序。我一直在tutorial上进行一些细微的修改,因为我不在Ubuntu机器上。 EC2实例正在运行RHEL Fedora。我不确定nginx为什么不将80上的流量路由到Gunicorn。
[当我激活虚拟环境并使用以下命令启动Gunicorn时:
gunicorn --bind 0.0.0.0:5000 --user ec2-user --workers 2 wsgi:app
我可以通过访问http://[mydomain].co:5000
成功访问我的应用。但是,当我更改bind
来监听袜子文件时:
gunicorn --bind unix:/home/ec2-user/run/myApp.sock --user ec2-user --group ec2-user --workers 2 wsgi:app
并在我的/etc/nginx/sites-available
中添加以下文件:
server {
listen 80;
server_name [mydomain].co www.[mydomain].co;
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/ec2-user/run/myApp.sock;
}
}
我无法访问我的网站。最初,我有一个问题,就是显然没有创建任何sock文件,因为当我ls /home/ec2-user/run/
目录为空时。我试着让Gunicorn监听127.0.0.1:5000
,然后将我的站点nginx conf文件更改为proxy_pass http://127.0.0.1:5000
,以查看是否可行,但也没有运气。
[我读过this answer,其中提到了更改用于放置Sock文件的文件夹的权限,但是我认为这不是我的问题。该文件夹的权限为:
drwxrwxr-x 2 ec2-user ec2-user 4096 Jun 13 02:44 /home/ec2-user/run/
FWIW,当我开始将gunicorn绑定到袜子文件时,它开始没有错误,并说它正在那个袜子文件位置监听,唯一的是那里似乎没有任何文件,所以我很迷路。感谢您提供的所有帮助或说明。
这似乎是权限问题。在我的ec2机器上,我这样做并为我工作。
创建系统服务文件
sudo nano /etc/systemd/system/myapi.service
文件内容如下:
[Unit]
Description=this is my test flask api
After=network.target
[Service]
User=ec2-user
Group=nginx
WorkingDirectory=/path/to/flaskapp
Environment="PATH=/path/to/flaskapp/.env/bin"
ExecStart=/path/to/flaskapp/.env/bin/gunicorn --workers 3 --bind unix:myapi.sock -m 007 wsgi
Restart=always
[Install]
WantedBy=multi-user.target
然后启动服务
sudo systemctl enable myapi
sudo systemctl start myapi
sudo systemctl status myapi
现在,您应该能够在flaskapp目录中看到套接字文件然后您可以创建一个nginx config
sudo nano /etc/nginx/sites-available/myapi
sudo ln -s /etc/nginx/sites-available/myapi /etc/nginx/sites-enabled
myapi.conf
server {
listen 8080;
server_name _;
location / {
proxy_pass http://unix:/path/to/flaskapp/myapi.sock;
}
}
server_name“ _”表示该服务器捕获了所有可能的值。
sudo chmod 710 /home/ec2-user
sudo usermod -aG ec2-user nignx
重新启动服务并测试URL
sudo nginx -t
sudo systemctl restart nginx
sudo systemctl status nginx
curl http://localhost:8080