Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure a Python as a service in AWS EC2

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?

like image 656
Eran Avatar asked Aug 19 '18 08:08

Eran


2 Answers

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.

like image 120
moebius Avatar answered Sep 30 '22 14:09

moebius


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.

like image 44
Patrick Otto Avatar answered Sep 30 '22 16:09

Patrick Otto