Wednesday, February 7, 2024

[SOLVED] Unable to run flask application as a service with systemd on Centos 7 server

Issue

I'm able to run flask app within virtualenv /web_services/flask_api/flask_api like this:

gunicorn --workers=4 --bind=localhost:8000 --log-level=error app:app

But, when I try to run it as a service it's not working. Here's a post that I followed to create a .service config file:

https://blog.miguelgrinberg.com/post/running-a-flask-application-as-a-service-with-systemd

Here's how my web_service.service file looks like:

[Unit]
Description=Sample web service
After=network.target 

[Service]
User=aaa.bbb
WorkingDirectory=/web_services/flask_api/flask_api
ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error web_service:app
Restart=always 

[Install]
WantedBy=multi-user.target

After saving this file I did:

$ sudo systemctl daemon-reload
$ sudo systemctl start web_service
$ sudo systemctl enable web_service

systemctl | grep running is not displaying this api.

While checking status of this service, I'm getting this:

sudo systemctl status web_service
● web_service.service - Sample web service  
 Loaded: loaded (/etc/systemd/system/web_service.service; enabled; vendor preset: disabled)   
 Active: failed (Result: start-limit) since Mon 2020-06-01 16:15:15 EDT; 13s ago 
 Process: 1016 ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error web_service:app (code=exited, status=1/FAILURE)
 Main PID: 1016 (code=exited, status=1/FAILURE)

Don't know what I'm missing here or doing wrong. Any help would be appreciated..


Solution

It got solved by changing:

ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error web_service:app

to

ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error app:app



Answered By - sm925
Answer Checked By - Marie Seifert (WPSolving Admin)