在 AWS EC2 中将 Python 配置为服务 [英] Configure a Python as a service in AWS EC2

查看:17
本文介绍了在 AWS EC2 中将 Python 配置为服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Python 脚本配置为在 Amazon 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?

推荐答案

您可以在 ec2 实例上创建一个 systemd 服务来实现这一点.步骤是:

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

  1. 创建服务定义文件:

  1. Create a service definition file:

sudo vi /lib/systemd/system/mypythonservice.service

  • 添加 systemd 单元文件定义.您可以查看this 或 systemd 参考指南更多详情:

  • 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
    

  • 重新加载 systemd 守护进程:

  • Reload the systemd daemon:

    sudo systemctl daemon-reload
    

  • 启用服务在重启时启动:

  • Enable the service to start on reboot:

    sudo systemctl enable mypythonservice.service
    

  • 当然,您可以将所有这些添加为 EC2 实例用户数据脚本的一部分,以便在实例启动时自动配置.

    And of course you can add all of this as part of a EC2 Instance User Data script to automatically configure on instance launch.

    这篇关于在 AWS EC2 中将 Python 配置为服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆