在 Ubuntu 上部署 C++ 服务,通常包含 开发环境准备、编译、运行、守护进程管理、以及可选的生产化部署。下面给你一个从入门到生产可用的完整流程,你可以按需要取用。
sudo apt update && sudo apt upgrade -y
sudo apt install -y build-essential
检查:
g++ --version
make --version
hello_server.cpp#include <iostream>
#include <unistd.h>
int main() {
while (true) {
std::cout << "C++ service is running..." << std::endl;
sleep(5);
}
return 0;
}
g++ -O2 -std=c++17 hello_server.cpp -o hello_server
./hello_server
nohupnohup ./hello_server > server.log 2>&1 &
查看进程:
ps aux | grep hello_server
停止服务:
kill PID
⚠️ 不推荐用于生产环境
sudo mkdir -p /opt/hello_server
sudo cp hello_server /opt/hello_server/
sudo vim /etc/systemd/system/hello_server.service
内容示例:
[Unit]
Description=Hello C++ Service
After=network.target
[Service]
Type=simple
ExecStart=/opt/hello_server/hello_server
WorkingDirectory=/opt/hello_server
Restart=always
RestartSec=5
StandardOutput=append:/var/log/hello_server.log
StandardError=append:/var/log/hello_server.log
[Install]
WantedBy=multi-user.target
sudo touch /var/log/hello_server.log
sudo chmod 644 /var/log/hello_server.log
sudo systemctl daemon-reload
sudo systemctl start hello_server
sudo systemctl enable hello_server
systemctl status hello_server
journalctl -u hello_server -f
cmake_minimum_required(VERSION 3.10)
project(hello_server)
set(CMAKE_CXX_STANDARD 17)
add_executable(hello_server main.cpp)
构建:
mkdir build && cd build
cmake ..
make
sudo apt install -y libboost-all-dev
例如:
FROM ubuntu:22.04
RUN apt update && apt install -y g++ cmake
WORKDIR /app
COPY . .
RUN mkdir build && cd build && cmake .. && make
CMD ["./build/hello_server"]
构建并运行:
docker build -t hello_server .
docker run -d --name hello_srv hello_server
| 场景 | 推荐方案 |
|---|---|
| 简单后台服务 | systemd |
| 高并发网络服务 | C++ + epoll / Boost.Asio |
| 微服务 | Docker + systemd |
| 云服务器 | Docker + Nginx + systemd |
✅ 使用 systemd 的 Restart=always
#include <sys/socket.h>
或使用网络库(推荐)
你可以告诉我:
我可以直接给你 可运行的完整项目模板。