在 Linux 上用 C++ 部署服务,通常包含 开发 → 编译 → 部署 → 运行 → 守护/自启 → 运维 几个阶段。下面给你一个常见、实用的完整流程,偏生产环境。
常见 C++ 服务类型:
| 功能 | 常用方案 |
|---|---|
| 网络 | epoll / libevent / asio / gRPC |
| 日志 | spdlog / glog |
| 配置 | json / yaml / ini |
| 打包 | CMake |
| 守护 | systemd |
| 容器 | Docker |
cmake_minimum_required(VERSION 3.10)
project(my_service)
set(CMAKE_CXX_STANDARD 17)
add_executable(my_service main.cpp)
mkdir build
cd build
cmake ..
make -j
生成:
my_service
/opt/my_service/
├── bin/
│ └── my_service # 可执行文件
├── conf/
│ └── config.json
├── log/
└── run/
scp my_service user@server:/opt/my_service/bin/
或直接在服务器编译。
cd /opt/my_service/bin
./my_service
✅ 确认:
sudo vim /etc/systemd/system/my_service.service
[Unit]
Description=My C++ Service
After=network.target
[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/my_service
ExecStart=/opt/my_service/bin/my_service
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start my_service
sudo systemctl enable my_service
systemctl status my_service
journalctl -u my_service -f
FROM ubuntu:22.04
WORKDIR /app
COPY my_service /app/
COPY config.json /app/
CMD ["./my_service"]
docker build -t my_service .
docker run -d --name my_service my_service
✅ 适合:
Restart=alwaysrestart: alwaysnetstat -tunlp | grep 8080
chmod +x my_service
nohup ./my_service > log.txt 2>&1 &
✅ 使用 systemd / Docker
✅ 日志统一输出(journal / 文件)
✅ 配置与代码分离
✅ 使用非 root 用户运行
✅ 增加健康检查接口
你可以直接说:
“我想做一个 HTTP / TCP / gRPC 服务”
“我是新手,给个完整示例”
“我要用 Docker 部署”