ubuntu

Ubuntu中Golang编译后的程序如何部署

小樊
34
2025-12-28 05:53:42
栏目: 编程语言

在Ubuntu中,部署Golang编译后的程序相对简单。以下是一些基本步骤:

  1. 编译Golang程序: 在你的Golang项目目录中,运行以下命令来编译你的程序:

    go build -o your_program_name
    

    这将在当前目录下生成一个名为your_program_name的可执行文件。

  2. 将可执行文件传输到目标服务器: 使用scp(安全复制)或其他文件传输方法将编译后的可执行文件传输到目标Ubuntu服务器。例如:

    scp your_program_name user@remote_host:/path/to/destination
    

    其中,user是远程服务器的用户名,remote_host是远程服务器的IP地址或主机名,/path/to/destination是你要将文件传输到的目标路径。

  3. 在目标服务器上设置可执行文件的权限: 在目标服务器上,确保可执行文件具有适当的权限。运行以下命令:

    chmod +x /path/to/destination/your_program_name
    
  4. 运行程序: 在目标服务器上,使用以下命令运行程序:

    /path/to/destination/your_program_name
    
  5. (可选)设置程序为系统服务: 如果你希望程序在后台运行并在系统启动时自动启动,可以将其设置为系统服务。为此,请创建一个新的systemd服务文件:

    sudo nano /etc/systemd/system/your_program_name.service
    

    将以下内容粘贴到文件中,根据需要进行修改:

    [Unit]
    Description=Your Golang Program
    
    [Service]
    ExecStart=/path/to/destination/your_program_name
    Restart=always
    User=user
    Group=user
    Environment=PATH=/usr/bin:/usr/local/bin
    
    [Install]
    WantedBy=multi-user.target
    

    保存并关闭文件。然后运行以下命令以启用和启动服务:

    sudo systemctl enable your_program_name.service
    sudo systemctl start your_program_name.service
    

    若要检查服务状态,请运行:

    sudo systemctl status your_program_name.service
    

现在,你已经成功地在Ubuntu中部署了Golang编译后的程序。

0
看了该问题的人还看了