温馨提示×

如何在Ubuntu中使用Golang打包Web应用

小樊
34
2026-06-30 20:32:36
栏目: 编程语言

在 Ubuntu 中使用 Golang 打包 Web 应用,通常包括 编译可执行文件、处理静态资源、设置运行环境 等步骤。下面按常见场景给你一个完整、实用的指南。


一、准备环境

1. 安装 Go(如果还没装)

sudo apt update
sudo apt install -y golang-go

检查版本:

go version

建议 Go ≥ 1.20
如需新版本,可使用 https://go.dev/dl/


二、项目结构示例

假设你的 Web 项目结构如下:

my-web-app/
├── main.go
├── go.mod
├── static/
│   └── style.css
├── templates/
│   └── index.html

main.go 示例:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("static"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, Golang Web!")
    })

    http.ListenAndServe(":8080", nil)
}

三、本地编译打包

1. 普通编译(本地运行)

go build -o myweb
./myweb

2. 交叉编译(常见做法 ✅)

✅ Linux 可执行文件(Ubuntu 服务器)

GOOS=linux GOARCH=amd64 go build -o myweb

✅ Windows

GOOS=windows GOARCH=amd64 go build -o myweb.exe

✅ macOS

GOOS=darwin GOARCH=amd64 go build -o myweb

四、打包静态资源(重要)

Go Web 应用常见问题是:部署时找不到 static / templates 文件

✅ 方法一:使用 embed(推荐)

Go 1.16+ 支持 //go:embed

package main

import (
    "embed"
    "net/http"
)

//go:embed static templates
var content embed.FS

func main() {
    fs := http.FileServer(http.FS(content))
    http.Handle("/static/", fs)

    http.ListenAndServe(":8080", nil)
}

✅ 优点:

  • 静态资源打包进可执行文件
  • 单文件部署,最简单

✅ 方法二:外部目录(维护方便)

部署时目录结构保持:

myweb
static/
templates/

运行:

./myweb

五、压缩可执行文件(可选)

Go 默认不压缩,可用 upx

sudo apt install upx
upx myweb

六、部署到 Ubuntu 服务器

1. 上传文件

scp myweb user@server:/opt/myweb/

2. 设置权限

chmod +x /opt/myweb/myweb

3. 手动运行测试

/opt/myweb/myweb

七、使用 systemd 管理(推荐 ✅)

创建服务文件:

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

内容示例:

[Unit]
Description=My Golang Web App
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/opt/myweb
ExecStart=/opt/myweb/myweb
Restart=always

[Install]
WantedBy=multi-user.target

启动并设置开机自启:

sudo systemctl daemon-reload
sudo systemctl start myweb
sudo systemctl enable myweb

查看状态:

sudo systemctl status myweb

八、使用 Nginx 反向代理(生产环境)

sudo apt install nginx

配置:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
    }
}

九、常见问题

❓ 1. 找不到模板 / 静态文件

✅ 使用 embed绝对路径

❓ 2. 端口无法访问

✅ 检查防火墙:

sudo ufw allow 80
sudo ufw allow 8080

十、总结流程

✅ 编写代码
go build 编译
✅ 使用 embed 或保持目录
✅ systemd 管理
✅ Nginx 反向代理


如果你使用的是 Gin / Echo / Fiber 或想 Docker 打包,告诉我,我可以给你针对性方案。

0