8

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?

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

3 Comments

We use sysvinit and not systemd. Any suggestion for that?
I would also add systemctl start myservice.service to start the process and then check the status using systemctl status myservice.service to this answer.
2

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.

1 Comment

this really helped me alot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.