Go

线上服务怎么部署golang应用程序

Royal
2023-06-21 / 0 评论 / 178 阅读 / 正在检测是否收录...
  1. 编译我们的golang项目并生成可执行程序(二进制文件)

    go build main.go

    lj5dt7j8.png

  2. 我们需要考虑将应用程序作为系统服务运行。为此,我们需要编写一个systemd服务文件。在/etc/systemd/system/目录中,使用vim或nano等编辑器创建一个新文件,文件名称为devcloud.service,当然您也可以为其取其他的名称
    lj5dvdzv.png
  3. 在devcloud.service文件中,添加以下内容:

    [Unit]
    Description=devcloud
    After=syslog.target
    After=network.target
    
    [Service]
    # Modify these two values and uncomment them if you have
    # repos with lots of files and get an HTTP error 500 because
    # of that
    ###
    #LimitMEMLOCK=infinity
    LimitNOFILE=100000
    LimitNPROC=100000
    Type=forking  # 如果要启动的命令是一个daemon进程, 这里的值设置为forking
    User=root
    Group=root
    # WorkingDirectory,程序的运行目录
    WorkingDirectory=/home/goproject/src
    # ExecStart,程序的启动命令,必须为绝对路径,若WorkingDirectory有变动,ExecStart路径对应也要变动
    ExecStart=/home/goproject/src/main
    Restart=always
    ExecStop=/bin/kill -9 $(pidof main)
    
    # Some distributions may not support these hardening directives. If you cannot start the service due
    # to an unknown option, comment out the ones not supported by your version of systemd.
    # ProtectSystem=full
    # PrivateDevices=yes
    # PrivateTmp=yes
    # NoNewPrivileges=true
    
    [Install]
    WantedBy=multi-user.target
    注释:常见的Type类型有以下这些:
    在Systemd配置文件中,常见的Type选项的取值有以下几种类型:
    simple:默认类型。当该服务以Type=simple启动时,Systemd会认为启动命令是简单的,不会进一步检查进程的状态。Systemd仅仅启动命令,并认为启动完成后服务已经就绪。
    forking:当服务启动时,Systemd会认为启动命令会派生(fork)出一个子进程,并认为服务在子进程就绪后才完成启动。此类型的服务会在主进程退出后仍然继续运行。
    oneshot:适用于只执行一次任务的服务。当服务启动时,Systemd会等待命令执行完成,然后认为服务已经完成启动。
    dbus:适用于通过DBus启动的服务。
    notify:适用于服务启动完成后向Systemd发送通知的情况。
    idle:适用于服务在空闲状态时启动的情况。
    exec:仅执行一次命令,不会认为服务在命令执行完成后就绪。
    以上是常见的Type选项的取值类型。根据您的需求和服务的特性,选择适合的Type选项来定义服务的启动类型。
  4. 保存文件后,使用以下命令启动新的系统服务并将其添加到自动启动中:

    systemctl start  devcloud
    systemctl enable devcloud
  5. 执行以上命令后,您的服务应该已经在Linux服务器上成功运行并自动启动,可以使用以下命令查看服务启动状态:

    systemctl status devcloud

    lj5e44nd.png

  6. 重启/停止服务

    systemctl restart  devcloud
    systemctl stop  devcloud
0

评论

博主关闭了当前页面的评论