5

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?

Eran
  • 527
  • 8
  • 15

2 Answers2

16

You can create a systemd service on the ec2 instance to achieve this. Steps are:

  1. Create a service definition file:

    sudo vi /lib/systemd/system/mypythonservice.service
    
  2. 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
    
  3. Set the necessary permissions on the file:

    sudo chmod 644 /lib/systemd/system/mypythonservice.service
    
  4. Reload the systemd daemon:

    sudo systemctl daemon-reload
    
  5. 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.

QueueHammer
  • 10,515
  • 12
  • 67
  • 91
moebius
  • 2,061
  • 11
  • 20
  • We use sysvinit and not systemd. Any suggestion for that? – Eran Aug 20 '18 at 09:03
  • You can have a look at this https://stackoverflow.com/questions/16420092/how-to-make-python-script-run-as-service or this: https://gist.github.com/int64ago/01fe54e45ffc28442c20 – moebius Aug 20 '18 at 09:24
1

aws and python logo

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.

Patrick Otto
  • 171
  • 2
  • 6