Reputation: 555
How do I configure a Python script to run as a service (re-launch on system restart, restart on failure) in Amazon AWS EC2 instance?
Upvotes: 8
Views: 6487
Reputation: 2259
You can create a systemd
service on the ec2 instance to achieve this. Steps are:
Create a service definition file:
sudo vi /lib/systemd/system/mypythonservice.service
Add the systemd unit file definition. You can check this or the systemd reference guide for more details:
[Unit]
Description=My Python Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python /home/myuser/mypythonproject.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
Set the necessary permissions on the file:
sudo chmod 644 /lib/systemd/system/mypythonservice.service
Reload the systemd daemon:
sudo systemctl daemon-reload
Enable the service to start on reboot:
sudo systemctl enable mypythonservice.service
And of course you can add all of this as part of a EC2 Instance User Data script to automatically configure on instance launch.
Upvotes: 18
Reputation: 181
Configure a Python as a service in AWS EC2
After much unsuccessful research to set up a Python API written on custom port 8080 to run on Amazon's Linux AMI operating system (AWS), I decided to solve this dilemma and share the solution with all of you.
See the solution in this link.
Upvotes: 2