温馨提示×

怎样在Debian跑Golang程序

小樊
44
2026-10-02 07:20:43
栏目: 编程语言

在 Debian 上运行 Golang 程序通常分为 安装 Go → 编写/获取代码 → 编译 → 运行 几个步骤。下面给你一套最常用、最稳妥的做法。


一、在 Debian 上安装 Go

方法 1:使用 Debian 官方仓库(简单,但版本可能偏旧)

sudo apt update
sudo apt install golang-go

查看版本:

go version

方法 2:官方二进制安装(推荐,版本新)

cd /tmp
wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz

添加到环境变量(~/.bashrc 或 ~/.profile):

export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go

使配置生效:

source ~/.bashrc

验证:

go version

二、编写并运行一个简单的 Golang 程序

1. 创建项目目录

mkdir ~/hello && cd ~/hello

2. 初始化模块

go mod init hello

3. 编写代码

nano main.go

内容示例:

package main

import "fmt"

func main() {
    fmt.Println("Hello Debian!")
}

4. 运行(不编译为二进制)

go run main.go

5. 编译并运行

go build -o hello
./hello

三、运行已有 Golang 项目

git clone https://github.com/xxx/yyy.git
cd yyy
go mod tidy
go run main.go
# 或
go build
./yyy

四、后台运行(生产常用)

使用 nohup

nohup ./hello > app.log 2>&1 &

使用 systemd(推荐)

创建服务文件:

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

内容:

[Unit]
Description=Go Hello Service
After=network.target

[Service]
ExecStart=/home/youruser/hello/hello
WorkingDirectory=/home/youruser/hello
User=youruser
Restart=always

[Install]
WantedBy=multi-user.target

启用并启动:

sudo systemctl daemon-reload
sudo systemctl enable hello
sudo systemctl start hello

查看状态:

sudo systemctl status hello

五、常见问题

1. go: command not found

说明 PATH 没配置好,检查:

which go
echo $PATH

2. 编译报错 missing go.sum

go mod tidy

3. 想交叉编译给其他系统

GOOS=linux GOARCH=arm64 go build

如果你愿意,可以告诉我:

  • 你是 桌面还是服务器
  • 是否要 开机自启
  • 是否是 Web 服务 / 爬虫 / CLI 工具

我可以给你更针对性的方案。

0 踩