# Linux

# nginx配置

配置文件[nginx.zip](http://10.8.0.4:4998/attachments/1)

## 引言

嗨，朋友们！今天我们要聊的主角，是 Web 服务器界的一颗璀璨明星 —— **Nginx**。如果你对这个名字不陌生，那肯定知道它有多厉害。全球超过三分之一的网站，包括 Netflix、Pinterest、Airbnb 这些流量巨兽，背后都有 Nginx 在默默支撑着。它就像一个轻量级的、高性能的“网站大管家”，既能当 Web 服务器，又能做反向代理，效率高到让你尖叫。

这次，我打算手把手教你如何在 **Ubuntu 22.04、24.04 乃至最新的 25.04** 系统上安装和配置 Nginx。别担心，这不仅仅是简单的安装步骤，我们会一起把防火墙设置、安全加固、性能优化，甚至一些常见问题的排查都搞定。跟着我，你会发现搭建一个高性能、安全的 Web 服务器，其实没那么难！

## <a class="reference-link" name="Nginx%EF%BC%9A%E4%BD%A0%E7%9A%84%E7%BD%91%E7%AB%99%E7%9A%84%E2%80%9C%E9%97%A8%E9%9D%A2%E2%80%9D%E5%92%8C%E2%80%9C%E5%A4%A7%E7%AE%A1%E5%AE%B6%E2%80%9D"></a>Nginx：你的网站的“门面”和“大管家”

在开始动手之前，我们先来快速看看通过这篇教程，你究竟能收获些什么“硬货”：

- **轻松安装与部署**：学会从 Ubuntu 官方软件源安装 Nginx，配置 `UFW` 防火墙规则，并验证安装是否成功。
- **服务管理得心应手**：掌握 `systemd` 命令，让你对 Nginx 服务的启停、重载、开机自启等操作了如指掌。
- **多站点托管秘籍**：通过配置 `Server Blocks`（Nginx 版的虚拟主机），在一台服务器上轻松托管多个域名。
- **安全防护升级**：应用一系列安全最佳实践，包括 `SSL/TLS` 证书（如 `Let's Encrypt`）、安全响应头、请求限速以及访问控制。
- **性能调优专家**：学会调整 `worker processes`、`connection limits`、缓存和 `Gzip` 压缩，让你的网站飞沙走石，速度爆表。
- **反向代理与负载均衡**：了解如何将 Nginx 设置为后端应用的 `Reverse Proxy`，甚至实现简单的负载均衡。
- **故障排除与日志分析**：学会查看 `access` 和 `error logs`，诊断常见问题，迅速定位并解决故障。
- **版本兼容性洞察**：理解 Ubuntu 22.04、24.04 和 25.04 在部署 Nginx 时的主要区别。
- **日常维护与监控**：建立备份机制，实施监控，并通过定期更新来保持服务器的健康状态。
- **生产环境准备**：最终目标是部署一个安全、优化且配置良好的 Nginx 服务器，能够从容应对生产环境的挑战！

是不是很期待？好啦，话不多说，我们这就开始吧！

## <a class="reference-link" name="%E9%83%A8%E7%BD%B2%E5%89%8D%E7%9A%84%E5%B0%8F%E5%87%86%E5%A4%87"></a>部署前的小准备

在正式开始 Nginx 的安装和配置之前，我们需要做一些基础准备工作，确保一切顺利进行。

你得准备好：

- **一台 Ubuntu 服务器**：可以是 Ubuntu 22.04 LTS、24.04 LTS 或者 25.04 的任意一台。如果你还没准备好，可以参考 DigitalOcean 的 [Ubuntu 服务器初始设置指南](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu)。
- **一个非 root 用户**：并且这个用户拥有 `sudo` 权限。为了服务器的安全，我们通常不直接使用 `root` 用户进行日常操作。如果还没有，可以跟着 [如何在 Ubuntu 上创建具有 sudo 权限的用户](https://www.digitalocean.com/community/tutorials/how-to-create-a-new-sudo-enabled-user-on-ubuntu) 这篇教程来搞定。
- **一个域名（可选）**：如果你想配置 `Server Blocks` 或者 `SSL` 证书，那就需要一个域名。如果你用的是 DigitalOcean，可以看看 [DigitalOcean DNS 简介](https://www.digitalocean.com/community/tutorials/an-introduction-to-digitalocean-dns) 来了解如何设置。
- **基础的命令行操作知识**：知道怎么在终端里敲命令就行，不用特别精通。

都准备好了吗？那就用你的非 `root` 用户登录服务器，我们开始折腾！

### <a class="reference-link" name="Ubuntu%20%E7%89%88%E6%9C%AC%E5%85%BC%E5%AE%B9%E6%80%A7%E4%B8%80%E8%A7%88"></a>Ubuntu 版本兼容性一览

不同版本的 Ubuntu 会自带不同版本的 Nginx，虽然安装方法基本一致，但了解一下版本差异还是有好处的：

<div id="bkmrk-ubuntu-%E7%89%88%E6%9C%AC-nginx-%E7%89%88%E6%9C%AC-%E6%94%AF"><table><thead><tr><th>Ubuntu 版本</th><th>Nginx 版本</th><th>支持状态</th><th>备注</th></tr></thead><tbody><tr><td>Ubuntu 22.04 LTS</td><td>1.18.0+</td><td>完全支持</td><td>长期支持，直至 2027 年</td></tr><tr><td>Ubuntu 24.04 LTS</td><td>1.24.0+</td><td>完全支持</td><td>最新 LTS 版本，增强了安全性</td></tr><tr><td>Ubuntu 25.04</td><td>1.26.0+</td><td>完全支持</td><td>最新特性和性能改进，更适合尝鲜</td></tr></tbody></table>

</div>## <a class="reference-link" name="%E7%AC%AC%E4%B8%80%E6%AD%A5%EF%BC%9A%E5%AE%89%E8%A3%85%20Nginx%20%E2%80%94%E2%80%94%20%E8%BD%BB%E6%9D%BE%E6%90%9E%E5%AE%9A%EF%BC%81"></a>第一步：安装 Nginx —— 轻松搞定！

Nginx 在所有受支持的 Ubuntu 版本中都可以通过默认的软件源获取。我们将使用 `apt` 包管理系统来安装最新的稳定版本。

### <a class="reference-link" name="%E6%9B%B4%E6%96%B0%E4%BD%A0%E7%9A%84%E7%B3%BB%E7%BB%9F"></a>更新你的系统

在安装任何新软件之前，老规矩，先更新一下你的本地包索引和所有已安装的软件包，确保我们获取到的是最新、最稳定的版本：

```
sudo apt update
sudo apt upgrade -y

```

`apt update` 会刷新本地的包列表，而 `apt upgrade -y` 则会升级所有可升级的软件包，`-y` 参数是自动确认，省得你每次都按 `Y`。

### <a class="reference-link" name="%E5%AE%89%E8%A3%85%20Nginx"></a>安装 Nginx

现在，激动人心的时刻到了！用下面这行命令就能安装 Nginx：

```
sudo apt install nginx -y

```

如果系统提示你确认安装，直接敲 `Y` 回车就好。如果还问你是否要重启某些服务，也直接敲 `Enter` 接受默认设置即可。`apt` 会自动帮你安装 Nginx 及其所有必要的依赖项。

### <a class="reference-link" name="%E9%AA%8C%E8%AF%81%E5%AE%89%E8%A3%85%E6%98%AF%E5%90%A6%E6%88%90%E5%8A%9F"></a>验证安装是否成功

安装完成后，我们可以快速检查一下 Nginx 的版本，确保安装没问题：

```
nginx -v

```

你应该会看到类似这样的输出，这表示 Nginx 已经成功安装：

```
nginx version: nginx/1.24.0 (Ubuntu)

```

Copy

### <a class="reference-link" name="%E6%A3%80%E6%9F%A5%20Nginx%20%E6%9C%8D%E5%8A%A1%E7%8A%B6%E6%80%81"></a>检查 Nginx 服务状态

Nginx 安装完成后，Ubuntu 通常会自动启动它。为了确认 Nginx 服务已经在后台正常运行，我们可以使用 `systemd` 这个初始化系统来检查：

```
systemctl status nginx

```

如果一切正常，你会看到类似这样的输出，其中 `Active: active (running)` 最为关键，它表明 Nginx 正在愉快地运行着：

```
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2022-03-01 16:08:19 UTC; 3 days ago
     Docs: man:nginx(8)
 Main PID: 2369 (nginx)
    Tasks: 2 (limit: 1153)
   Memory: 3.5M
   CGroup: /system.slice/nginx.service
           ├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           └─2380 nginx: worker process

```

虽然 `systemctl` 已经告诉我们服务启动成功了，但最直接的验证方法是亲自从浏览器访问 Nginx 的默认页面。

如果你不确定服务器的公网 IP 地址，可以用 `icanhazip.com` 这个小工具快速获取：

```
curl -4 icanhazip.com

```

拿到你的服务器 IP 地址后，把它输入到你的浏览器地址栏：

```
http://你的服务器_IP

```

如果一切顺利，你将会看到 Nginx 的默认欢迎页面，通常长这样：

![Nginx default page](https://assets.digitalocean.com/articles/nginx_1604/default_page.png)

恭喜你！看到这个页面，就说明你的 Web 服务器已经成功启动并可以正常访问了。

## <a class="reference-link" name="%E7%AC%AC%E4%BA%8C%E6%AD%A5%EF%BC%9A%E9%98%B2%E7%81%AB%E5%A2%99%20UFW%20%E8%AE%BE%E7%BD%AE%20%E2%80%94%E2%80%94%20%E5%AE%89%E5%85%A8%E7%AC%AC%E4%B8%80%EF%BC%81"></a>第二步：防火墙 UFW 设置 —— 安全第一！

在让 Nginx 对外提供服务之前，**防火墙**是必须配置的“门卫”。想象一下，你的服务器就像一个家，防火墙就是大门。我们得告诉它，哪些人可以进来，哪些端口可以被访问。好在 Nginx 在安装时很贴心地在 `ufw` 中注册了自己，让我们的配置变得非常简单。

首先，我们来看看 `ufw` 知道哪些应用配置：

```
sudo ufw app list

```

你会看到类似这样的应用配置文件列表：

```
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

```

这里有三个 Nginx 相关的配置文件：

- **Nginx Full**：这个配置文件会同时打开 80 端口（用于普通的未加密 HTTP 网页流量）和 443 端口（用于 `TLS/SSL` 加密的 HTTPS 流量）。
- **Nginx HTTP**：这个配置文件只打开 80 端口（用于普通的未加密 HTTP 网页流量）。
- **Nginx HTTPS**：这个配置文件只打开 443 端口（用于 `TLS/SSL` 加密的 HTTPS 流量）。
- **OpenSSH**: 这个是 SSH 服务，用来远程登录你的服务器。**友情提示：在配置防火墙时，一定要记得允许 `OpenSSH`，否则你可能会被自己锁在服务器外面！**

通常，我们建议你启用最严格的防火墙配置文件，只允许你实际需要的流量通过。现在，我们只需要允许 HTTP 流量（80 端口），所以选择 `Nginx HTTP` 就够了。

启用它：

```
sudo ufw allow 'Nginx HTTP'
# 别忘了，如果你之前没有允许过 OpenSSH，现在也把它加上！
sudo ufw allow 'OpenSSH'

```

你现在可以验证防火墙规则是否已生效：

```
sudo ufw status

```

输出会显示哪些 HTTP 流量被允许了：

```
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                  
Nginx HTTP                 ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)             
Nginx HTTP (v6)            ALLOW       Anywhere (v6)

```

看到 `Nginx HTTP` 和 `OpenSSH` 都显示为 `ALLOW` 了吗？这意味着你的网站对外开放了 HTTP 访问，同时你还能通过 SSH 登录管理服务器，安全又方便！

## <a class="reference-link" name="%E7%AC%AC%E4%B8%89%E6%AD%A5%EF%BC%9A%E6%A3%80%E6%9F%A5%E4%BD%A0%E7%9A%84%20Web%20%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%98%AF%E5%90%A6%E6%B4%BB%E8%B9%A6%E4%B9%B1%E8%B7%B3"></a>第三步：检查你的 Web 服务器是否活蹦乱跳

虽然我们已经在第二步中验证了 Nginx 服务是否运行，但再用最直接的方式确认一下，总没错！

Nginx 安装完成后，Ubuntu 就会自动启动它，所以理论上，你的 Web 服务器现在应该已经处于运行状态了。

我们已经用 `systemctl status nginx` 确认过了服务的后台状态。现在，让我们直接通过浏览器访问你的服务器 IP 地址，看看 Nginx 的欢迎页面能不能正常显示。

如果你不确定服务器的公共 IP 地址，可以像之前一样，使用 `curl -4 icanhazip.com` 命令来获取。

拿到 IP 后，在你的浏览器地址栏输入：

```
http://你的_服务器_IP

```

Copy

比如 `http://203.0.113.1`。

如果一切顺利，你将再次看到 Nginx 默认的“Welcome to Nginx!”页面。这就像是 Nginx 在跟你打招呼，告诉你：“我准备好为你服务了！”

看到这个页面就说明 Nginx 已经成功部署，并且可以正常地通过互联网访问，随时准备好承载你的网站内容了。

## <a class="reference-link" name="%E7%AC%AC%E5%9B%9B%E6%AD%A5%EF%BC%9A%E7%AE%A1%E7%90%86%20Nginx%20%E8%BF%9B%E7%A8%8B%20%E2%80%94%E2%80%94%20%E9%9A%8F%E5%BF%83%E6%89%80%E6%AC%B2"></a>第四步：管理 Nginx 进程 —— 随心所欲

现在你的 Web 服务器已经上线了，接下来学习一些基本的管理命令，让你能像驾驭一匹骏马一样，灵活控制 Nginx。这些命令主要通过 `systemctl` 来操作 `systemd` 服务管理系统。

**停止你的 Web 服务器：**

当你需要暂时关闭 Nginx 服务时，比如进行维护或者升级，可以使用这个命令：

```
sudo systemctl stop nginx

```

**启动已停止的 Web 服务器：**

当 Nginx 停止后，你需要重新启动它时：

```
sudo systemctl start nginx

```

**停止后再启动服务（重启）：**

这是一个常用的命令，当你修改了 Nginx 的配置后，通常需要重启服务来应用这些改动。它会先停止服务，再重新启动：

```
sudo systemctl restart nginx

```

**重新加载配置（不中断连接）：**

Nginx 最酷的功能之一是，当你只修改了配置文件（而不是 Nginx 本身的核心功能）时，它可以**无缝重新加载配置，而不会中断现有的用户连接**。这对于生产环境中的网站来说至关重要，用户根本感觉不到服务有任何中断！

```
sudo systemctl reload nginx

```

**禁止 Nginx 开机自启：**

默认情况下，Nginx 会被配置成在服务器启动时自动运行。如果你不希望它这样做，比如你只在特定时间运行服务，或者有其他启动顺序要求，可以禁用这个行为：

```
sudo systemctl disable nginx

```

**重新启用 Nginx 开机自启：**

如果你改变了主意，想让 Nginx 再次在开机时自动启动，可以重新启用服务：

```
sudo systemctl enable nginx

```

掌握了这些基本的管理命令，你就有了驾驭 Nginx 的能力。接下来，我们将学习如何配置 `Server Blocks`，让一台服务器承载多个网站！

## <a class="reference-link" name="%E7%AC%AC%E4%BA%94%E6%AD%A5%EF%BC%9A%E9%85%8D%E7%BD%AE%20Server%20Blocks%EF%BC%88%E8%99%9A%E6%8B%9F%E4%B8%BB%E6%9C%BA%EF%BC%89%E2%80%94%E2%80%94%20%E4%B8%80%E5%8F%B0%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%8C%E5%A4%9A%E4%B8%AA%E7%BD%91%E7%AB%99%EF%BC%81"></a>第五步：配置 Server Blocks（虚拟主机）—— 一台服务器，多个网站！

想象一下，你的服务器就像一栋公寓楼，而 `Server Blocks`（在 Apache 中我们叫它虚拟主机 `virtual hosts`）就是这栋楼里的不同房间。每个房间都可以住进一个不同的“租客”（网站），拥有自己独立的配置和内容，但都共享同一栋楼的资源。

我们将以一个叫做 **`your_domain`** 的域名为例进行设置，但在实际操作中，你**务必将其替换为你自己的真实域名**。

在 Ubuntu 22.04 上，Nginx 默认会启用一个 `Server Block`，它的文档根目录在 `/var/www/html`。对于单个网站来说，这很方便。但如果你想托管多个网站，直接修改这个目录就会变得很混乱。所以，我们的策略是：保留 `/var/www/html` 作为默认的“备用”目录（当用户的请求不匹配任何其他网站时），然后为我们的 `your_domain` 网站在 `/var/www` 下创建一个新的、独立的目录结构。

### <a class="reference-link" name="1.%20%E5%88%9B%E5%BB%BA%E7%BD%91%E7%AB%99%E7%9B%AE%E5%BD%95"></a>1. 创建网站目录

首先，为你的域名创建一个目录结构，`html` 子目录是存放网站文件的标准位置。`-p` 参数会确保所有必要的父目录都被创建：

```
sudo mkdir -p /var/www/your_domain/html

```

### <a class="reference-link" name="2.%20%E5%88%86%E9%85%8D%E7%9B%AE%E5%BD%95%E6%89%80%E6%9C%89%E6%9D%83"></a>2. 分配目录所有权

接下来，我们需要将这个新目录的所有权分配给你的当前用户（`$USER` 环境变量代表你当前登录的用户名）。这样你就可以在不需要 `sudo` 的情况下，轻松地在其中创建、修改文件：

```
sudo chown -R $USER:$USER /var/www/your_domain/html

```

### <a class="reference-link" name="3.%20%E8%AE%BE%E7%BD%AE%E7%9B%AE%E5%BD%95%E6%9D%83%E9%99%90"></a>3. 设置目录权限

为了确保 Web 服务器能够读取文件，同时保证安全，我们需要设置合适的目录权限。`755` 权限意味着所有者拥有读、写、执行的完整权限，而用户组和其他人只有读和执行的权限。

```
sudo chmod -R 755 /var/www/your_domain

```

### <a class="reference-link" name="4.%20%E5%88%9B%E5%BB%BA%E7%A4%BA%E4%BE%8B%20<code>index.html</code>%20%E6%96%87%E4%BB%B6"></a>4. 创建示例 `index.html` 文件

现在，我们来为 `your_domain` 创建一个简单的 `index.html` 页面。你可以用 `nano` 或你喜欢的任何文本编辑器：

```
nano /var/www/your_domain/html/index.html

```

在文件中添加以下 `HTML` 内容。别忘了把 `your_domain` 替换成你的实际域名：

```

<html>
    <head>
        <title>欢迎来到 your_domain!</title>
    </head>
    <body>
        <h1>恭喜！ your_domain 的 Server Block 运行成功！</h1>
        <p>这是你的自定义网站页面。</p>
    </body>
</html>

```

保存并关闭文件。在 `nano` 中，按 `Ctrl+X`，然后按 `Y` 确认保存，最后按 `Enter`。

### <a class="reference-link" name="5.%20%E5%88%9B%E5%BB%BA%E6%96%B0%E7%9A%84%20<code>Server%20Block</code>%20%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"></a>5. 创建新的 `Server Block` 配置文件

为了让 Nginx 知道如何处理 `your_domain` 的请求，我们需要创建一个专门的 `Server Block` 配置文件。我们不会直接修改默认配置，而是在 `/etc/nginx/sites-available/` 目录下创建新文件：

```
sudo nano /etc/nginx/sites-available/your_domain

```

粘贴以下配置代码块。这个配置与默认的类似，但我们更新了 `root` 目录和 `server_name`：

```
server {
        listen 80;
        listen [::]:80;

        root /var/www/your_domain/html;
        index index.html index.htm index.nginx-debian.html;

        server_name your_domain www.your_domain;

        location / {
                try_files $uri $uri/ =404;
        }
}

```

这里简单解释一下：

- `listen 80;`：Nginx 监听 80 端口，处理 HTTP 请求。`listen [::]:80;` 确保也监听 IPv6 地址。
- `root /var/www/your_domain/html;`：指定网站文件的根目录。
- `index index.html ...;`：定义当访问目录时，Nginx 尝试加载的文件名顺序。
- `server_name your_domain www.your_domain;`：指定这个 `Server Block` 会响应哪些域名请求。
- `location / {}`：定义了请求如何路由。`try_files $uri $uri/ =404;` 表示 Nginx 会尝试查找与 `URI` 匹配的文件，如果没有找到文件就查找目录，如果都找不到，则返回 404 错误。

### <a class="reference-link" name="6.%20%E5%90%AF%E7%94%A8%20<code>Server%20Block</code>"></a>6. 启用 `Server Block`

现在，我们的新 `Server Block` 配置文件还在 `sites-available` 目录里，Nginx 默认不会读取它。我们需要通过创建一个**符号链接（symlink）**，把它“链接”到 `sites-enabled` 目录，Nginx 在启动时会读取这个目录下的所有配置文件：

```
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/

```

> **小贴士**：符号链接就像是文件系统里的“快捷方式”。这样做的好处是，你可以轻松地禁用一个 `Server Block`（只需删除 `sites-enabled` 里的链接），而不用删除原始的配置文件，以后想再启用时很方便。

现在，你的 Nginx 服务器上有了两个活跃的 `Server Block`：

- `your_domain`：响应 `your_domain` 和 `www.your_domain` 的请求。
- `default`：如果任何请求不匹配 `your_domain` 的 `Server Block`，它会由默认的 `Server Block` 来处理（通常是 `/var/www/html` 里的内容）。

### <a class="reference-link" name="7.%20%E8%B0%83%E6%95%B4%20<code>nginx.conf</code>%20%E6%96%87%E4%BB%B6"></a>7. 调整 `nginx.conf` 文件

为了避免潜在的 `hash bucket memory` 问题（当有大量 `server_name` 时可能出现），我们还需要稍微调整一下主配置文件 `/etc/nginx/nginx.conf`。

打开这个文件：

```
sudo nano /etc/nginx/nginx.conf

```

在 `http { ... }` 配置块内，找到 `server_names_hash_bucket_size` 这行。它可能被注释掉了（前面有一个 `#` 符号）。我们需要取消注释，并确保它的值是 `64`：

```
...
http {
    ...
    server_names_hash_bucket_size 64; # 移除前面的 # 号
    ...
}
...

```

> **小贴士**：在配置文件中，用 `#` 符号注释掉一行代码是禁用它的常见做法，同时也能作为文档说明。很多配置文件会预留一些注释掉的选项，方便用户根据需求启用或禁用。

保存并关闭文件。

### <a class="reference-link" name="8.%20%E6%B5%8B%E8%AF%95%E9%85%8D%E7%BD%AE%E5%B9%B6%E9%87%8D%E5%90%AF%20Nginx"></a>8. 测试配置并重启 Nginx

在重启 Nginx 之前，**强烈建议**你先测试一下配置文件的语法是否正确，避免因为手误导致服务启动失败：

```
sudo nginx -t

```

如果没有任何语法错误，你会看到 `syntax is ok` 和 `test is successful` 的提示。如果出现错误，请仔细检查你刚才修改的文件。

测试通过后，重启 Nginx 服务，让新的 `Server Block` 生效：

```
sudo systemctl restart nginx

```

现在，Nginx 应该已经开始为你的域名提供服务了。打开你的浏览器，访问 `http://your_domain`（再次强调，替换成你的实际域名），你应该会看到你刚才创建的那个“恭喜！”页面。

![Nginx first server block](https://assets.digitalocean.com/articles/how-to-install-nginx-u18.04/your-domain-server-block-nginx.PNG)

是不是很酷？你已经成功在一台服务器上部署了你的第一个自定义网站！

## <a class="reference-link" name="%E7%AC%AC%E5%85%AD%E6%AD%A5%EF%BC%9A%E5%AE%89%E5%85%A8%E5%8A%A0%E5%9B%BA%E4%B8%8E%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%20%E2%80%94%E2%80%94%20%E8%AE%A9%E4%BD%A0%E7%9A%84%E7%BD%91%E7%AB%99%E5%8F%88%E5%BF%AB%E5%8F%88%E5%AE%89%E5%85%A8%EF%BC%81"></a>第六步：安全加固与性能优化 —— 让你的网站又快又安全！

网站上线了，但我们不能止步于此。一个优秀的 Web 服务器不仅要能正常工作，更要又快又安全。这一步，我们将为 Nginx 进行一些生产环境级别的安全加固和性能优化。

### <a class="reference-link" name="%E5%9F%BA%E7%A1%80%E5%AE%89%E5%85%A8%E9%85%8D%E7%BD%AE"></a>基础安全配置

编辑 Nginx 的主配置文件：

```
sudo nano /etc/nginx/nginx.conf

```

在 `http { ... }` 配置块内，添加以下安全相关的指令。它们能有效提高服务器的安全性，抵御一些常见的攻击：

```
# 隐藏 Nginx 版本信息，避免暴露服务器软件版本给攻击者
server_tokens off;

# 添加安全响应头，防止常见的 Web 漏洞
# X-Frame-Options: 防止点击劫持 (Clickjacking) 攻击
add_header X-Frame-Options "SAMEORIGIN" always;
# X-XSS-Protection: 启用浏览器内置的 XSS 防护
add_header X-XSS-Protection "1; mode=block" always;
# X-Content-Type-Options: 防止 MIME 类型嗅探攻击
add_header X-Content-Type-Options "nosniff" always;
# Referrer-Policy: 控制浏览器发送 Referer 头的信息
add_header Referrer-Policy "no-referrer-when-downgrade" always;
# Content-Security-Policy: 内容安全策略，限制可加载的资源来源，大大减少 XSS 风险
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

# 再次确认隐藏 Nginx 版本信息 (防止某些模块覆盖)
server_tokens off;

# 限制客户端请求体大小，防止恶意大文件上传导致服务器资源耗尽
client_max_body_size 10M; # 例如，限制为 10MB

# 超时设置，防止慢速攻击和资源占用
client_body_timeout 12s;    # 客户端发送请求体超时
client_header_timeout 12s;  # 客户端发送请求头超时
keepalive_timeout 15s;      # 长连接保持时间
send_timeout 10s;           # 服务器向客户端发送响应超时

```

### <a class="reference-link" name="%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%A7%98%E7%B1%8D"></a>性能优化秘籍

同样在 `/etc/nginx/nginx.conf` 文件中，添加以下性能优化配置。它们能帮助 Nginx 更高效地处理请求：

```
# Worker 进程数量 (根据你的 CPU 核心数进行调整)
# auto 表示 Nginx 会自动检测 CPU 核心数并设置相应数量的 worker 进程
worker_processes auto;

# Worker 连接设置
events {
    # 每个 worker 进程可以处理的最大并发连接数
    worker_connections 1024;
    # 使用高效的 I/O 多路复用机制，epoll 是 Linux 上的首选
    use epoll;
    # 允许 worker 进程一次性接受多个新连接
    multi_accept on;
}

# Gzip 压缩，显著减少传输数据量，加快页面加载速度
gzip on;
# 告诉代理服务器根据 Vary: Accept-Encoding 头来缓存压缩内容
gzip_vary on;
# 对所有代理请求的响应进行压缩
gzip_proxied any;
# 压缩级别，1（最低）到 9（最高），6 是一个很好的平衡点
gzip_comp_level 6;
# 定义哪些 MIME 类型的文件需要进行 Gzip 压缩
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml+rss
    application/atom+xml
    image/svg+xml;

```

### <a class="reference-link" name="%E6%B5%8B%E8%AF%95%E5%B9%B6%E5%BA%94%E7%94%A8%E9%85%8D%E7%BD%AE"></a>测试并应用配置

修改完配置文件后，老规矩，先测试语法，再重载 Nginx。

**测试配置：**

```
sudo nginx -t

```

**如果测试通过，重载 Nginx：**

```
sudo systemctl reload nginx

```

### <a class="reference-link" name="SSL/TLS%20%E8%AF%81%E4%B9%A6%E5%87%86%E5%A4%87"></a>SSL/TLS 证书准备

为了让你的网站支持 `HTTPS`，并启用 `Nginx HTTPS` 防火墙规则，你需要安装 `SSL/TLS` 证书。`Let's Encrypt` 提供免费且自动化的证书。

**安装 Certbot 工具：**

`Certbot` 是一个可以自动为 Nginx 获取和配置 `Let's Encrypt` 证书的工具。

```
# 安装 Certbot 及其 Nginx 插件
sudo apt install certbot python3-certbot-nginx -y

# 检查 Certbot 是否正常工作
sudo certbot --version

```

看到 `Certbot` 的版本号，就说明工具安装成功了。下一步就是使用它来为你的域名生成和配置证书。

通过这些安全加固和性能优化，你的 Nginx 服务器现在不仅更安全，而且能提供更快的用户体验。棒极了！

## <a class="reference-link" name="%E7%AC%AC%E4%B8%83%E6%AD%A5%EF%BC%9ANginx%20%E9%82%A3%E4%BA%9B%E9%87%8D%E8%A6%81%E7%9A%84%E6%96%87%E4%BB%B6%E5%92%8C%E7%9B%AE%E5%BD%95"></a>第七步：Nginx 那些重要的文件和目录

既然你已经和 Nginx 混熟了，了解它的一些“内部构造”会让你在管理和排查问题时事半功倍。Nginx 在 Ubuntu 上有一些关键的目录和文件，就像是它的“说明书”和“日记本”。

### <a class="reference-link" name="%E5%86%85%E5%AE%B9%E6%96%87%E4%BB%B6"></a>内容文件

- `/var/www/html`：这是 Nginx 默认的 Web 根目录。你之前看到的那个“Welcome to Nginx!”页面就存放在这里。当然，我们自己创建的 `Server Block` 会有自己的 `root` 目录，比如 `/var/www/your_domain/html`。
- **你自己的网站目录**：例如 `/var/www/your_domain/html`，这里存放着你的网站的所有 `HTML`、`CSS`、`JavaScript` 和图片等文件。

### <a class="reference-link" name="%E6%9C%8D%E5%8A%A1%E5%99%A8%E9%85%8D%E7%BD%AE"></a>服务器配置

- `/etc/nginx`：这是 Nginx 的主配置目录，所有的 Nginx 配置文件都住在这里。
- `/etc/nginx/nginx.conf`：Nginx 的**主配置文件**。你可以在这里修改 Nginx 的全局配置，比如 `worker_processes`、`gzip` 设置、`server_names_hash_bucket_size` 等。
- `/etc/nginx/sites-available/`：这个目录存放着所有**可用的 `Server Blocks` 配置文件**。你可以为每个网站创建一个独立的配置文件放在这里。Nginx 不会直接使用这些文件，除非它们被“链接”到 `sites-enabled` 目录。
- `/etc/nginx/sites-enabled/`：这个目录存放着所有**已启用的 `Server Blocks` 配置文件**。它们通常是通过符号链接指向 `sites-available` 目录下的文件。Nginx 在启动时会加载并执行这个目录中的所有配置。
- `/etc/nginx/snippets`：这个目录包含一些**配置片段**。如果你有一些重复出现的配置（比如 `SSL` 设置、安全响应头），可以把它们抽象成一个片段文件，然后在多个 `Server Blocks` 中引用，保持配置的整洁和可维护性。

### <a class="reference-link" name="%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%97%A5%E5%BF%97"></a>服务器日志

- `/var/log/nginx/access.log`：这是 Nginx 的**访问日志**。每一次用户对你网站的访问请求，无论成功与否，都会被记录在这个文件里。它包含了访问者的 IP、请求时间、请求方法、`URL`、状态码、响应大小等信息，是分析网站流量和用户行为的重要数据源。
- `/var/log/nginx/error.log`：这是 Nginx 的**错误日志**。任何 Nginx 自身运行时的错误、配置错误或者请求处理中的异常，都会被记录在这里。当你的网站出现问题时，查看这个日志文件是排查故障的第一步，它会告诉你发生了什么，在哪里发生了。

熟悉这些文件和目录，能让你在管理 Nginx 时更加得心应手，遇到问题也能快速找到线索，解决它们。

## <a class="reference-link" name="Nginx%20%E5%AE%89%E5%85%A8%E5%B0%8F%E8%B4%B4%E5%A3%AB%EF%BC%9A%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98%E4%B8%8E%E5%AE%9E%E8%B7%B5"></a>Nginx 安全小贴士：常见问题与实践

保障 Web 服务器的安全就像给你的网站穿上一层厚厚的盔甲。以下是一些 Nginx 安全加固的实践和常见问题，希望能帮到你：

### <a class="reference-link" name="Nginx%20%E5%AE%89%E5%85%A8%E5%AE%9E%E8%B7%B5%E6%B8%85%E5%8D%95"></a>Nginx 安全实践清单

<div id="bkmrk-%E5%AE%89%E5%85%A8%E5%AE%9E%E8%B7%B5-%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F-%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4%2F%E9%85%8D%E7%BD%AE-%E4%BC%98%E5%85%88"><table><thead><tr><th>安全实践</th><th>实现方式</th><th>常用命令/配置</th><th>优先级</th></tr></thead><tbody><tr><td>**保持 Nginx 更新**</td><td>定期更新 Nginx 及系统软件包</td><td>`sudo apt update && sudo apt upgrade nginx`</td><td>高</td></tr><tr><td>**配置防火墙**</td><td>使用 `UFW` 限制只开放必要端口</td><td>`sudo ufw allow 'Nginx Full'`</td><td>高</td></tr><tr><td>**启用 SSL/TLS**</td><td>使用 `Let's Encrypt` 安装 `SSL` 证书</td><td>`sudo certbot --nginx -d your_domain.com`</td><td>高</td></tr><tr><td>**隐藏服务器信息**</td><td>阻止 Nginx 版本泄露</td><td>在 `/etc/nginx/nginx.conf` 中添加 `server_tokens off;`</td><td>中</td></tr><tr><td>**安全响应头**</td><td>添加安全响应头，防止常见攻击</td><td>在 `server block` 中添加（见下方示例）</td><td>中</td></tr><tr><td>**请求限速**</td><td>配置 `rate limiting`，抵御 `DDoS` 和暴力破解攻击</td><td>配置 `limit_req_zone` 和 `limit_req`</td><td>中</td></tr><tr><td>**强认证**</td><td>为管理界面使用强密码</td><td>实施 HTTP 基本认证或 `OAuth`</td><td>中</td></tr><tr><td>**定期备份**</td><td>备份 Nginx 配置和网站内容</td><td>`sudo cp -r /etc/nginx /backup/nginx-$(date +%Y%m%d)`</td><td>中</td></tr><tr><td>**访问控制**</td><td>限制对敏感目录的访问</td><td>使用 `deny all;` 或 IP 白名单</td><td>低</td></tr><tr><td>**日志监控**</td><td>监控访问和错误日志，发现可疑活动</td><td>`sudo tail -f /var/log/nginx/error.log`</td><td>低</td></tr></tbody></table>

</div>### <a class="reference-link" name="%E7%A4%BA%E4%BE%8B%EF%BC%9A%E5%AE%89%E5%85%A8%E5%93%8D%E5%BA%94%E5%A4%B4%E9%85%8D%E7%BD%AE"></a>示例：安全响应头配置

为了进一步增强安全性，你可以在 `Server Block` 中添加这些响应头，它们可以有效防止一些常见的 Web 漏洞：

```
server {
    ...
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
    ...
}

```

### <a class="reference-link" name="%E7%A4%BA%E4%BE%8B%EF%BC%9A%E8%AF%B7%E6%B1%82%E9%99%90%E9%80%9F%E9%85%8D%E7%BD%AE"></a>示例：请求限速配置

请求限速是抵御 `DDoS` 攻击和暴力破解的有效手段。你可以在 `http` 块中定义一个限速区域，然后在 `Server Block` 或 `location` 块中应用它。

**第一步：在 `/etc/nginx/nginx.conf` 的 `http` 块中定义限速区域：**

```
http {
    ...
    # 定义一个名为 'one' 的限速区域，大小 10MB，每秒处理 1 个请求
    # $binary_remote_addr 用来识别客户端 IP 地址
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    ...
}

```

**第二步：在你的 `Server Block` 或 `location` 块中应用这个限速区域：**

```
server {
    ...
    # 对所有请求应用名为 'one' 的限速规则
    # burst=5 表示允许在短时间内突发 5 个请求，然后才开始限速
    # nodelay 表示不延迟处理突发请求，但超出突发限制的请求会被直接拒绝
    location / {
        limit_req zone=one burst=5 nodelay;
        try_files $uri $uri/ =404;
    }
    ...
}

```

## <a class="reference-link" name="%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98%20Q&A"></a>常见问题 Q&amp;A

我们整理了一些 Nginx 相关的常见问题，并提供了简明扼要的答案，希望对你有帮助。

### <a class="reference-link" name="1.%20%E5%A6%82%E4%BD%95%E5%90%AF%E5%8A%A8%E3%80%81%E5%81%9C%E6%AD%A2%E5%92%8C%E7%AE%A1%E7%90%86%20Nginx%20%E6%9C%8D%E5%8A%A1%EF%BC%9F"></a>1. 如何启动、停止和管理 Nginx 服务？

管理 Nginx 服务主要依赖 `systemctl` 命令：

```
# 启动 Nginx
sudo systemctl start nginx

# 停止 Nginx
sudo systemctl stop nginx

# 重启 Nginx (先停止再启动)
sudo systemctl restart nginx

# 重新加载配置 (不停止服务，不中断连接)
sudo systemctl reload nginx

# 设置 Nginx 开机自启
sudo systemctl enable nginx

# 禁用 Nginx 开机自启
sudo systemctl disable nginx

```

### <a class="reference-link" name="2.%20%E6%80%8E%E4%B9%88%E6%A3%80%E6%9F%A5%20Nginx%20%E6%98%AF%E5%90%A6%E6%AD%A3%E5%9C%A8%E8%BF%90%E8%A1%8C%EF%BC%9F"></a>2. 怎么检查 Nginx 是否正在运行？

你可以通过多种方式确认 Nginx 的运行状态：

```
# 检查服务状态（最常用）
sudo systemctl status nginx

# 检查 Nginx 是否监听了端口（比如 80 或 443）
sudo netstat -tlnp | grep nginx

# 测试 Nginx 配置文件语法是否正确
sudo nginx -t

# 查看 Nginx 进程
ps aux | grep nginx

```

### <a class="reference-link" name="3.%20%E5%A6%82%E4%BD%95%E4%B8%BA%20Nginx%20%E9%85%8D%E7%BD%AE%20UFW%20%E9%98%B2%E7%81%AB%E5%A2%99%EF%BC%9F"></a>3. 如何为 Nginx 配置 UFW 防火墙？

`UFW` 为 Nginx 提供了三种预设的配置文件，你可以根据需求选择：

```
    # 只允许 HTTP 流量 (端口 80)
    sudo ufw allow 'Nginx HTTP'

    # 只允许 HTTPS 流量 (端口 443)
    sudo ufw allow 'Nginx HTTPS'

    # 同时允许 HTTP 和 HTTPS 流量
    sudo ufw allow 'Nginx Full'

    # 检查 UFW 防火墙状态
    sudo ufw status

```

### <a class="reference-link" name="4.%20Ubuntu%20%E4%B8%8A%20Nginx%20%E7%9A%84%E9%BB%98%E8%AE%A4%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E5%9C%A8%E5%93%AA%EF%BC%9F"></a>4. Ubuntu 上 Nginx 的默认配置文件在哪？

- **主配置文件**：`/etc/nginx/nginx.conf`
- **可用站点配置**：`/etc/nginx/sites-available/` (存放所有站点配置，待启用)
- **已启用站点配置**：`/etc/nginx/sites-enabled/` (通过符号链接指向 `sites-available` 中的配置)
- **默认站点配置**：`/etc/nginx/sites-available/default` (Nginx 默认的站点配置)

### <a class="reference-link" name="5.%20%E5%A6%82%E4%BD%95%E5%B0%86%20Nginx%20%E9%85%8D%E7%BD%AE%E4%B8%BA%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86%EF%BC%9F"></a>5. 如何将 Nginx 配置为反向代理？

在 `/etc/nginx/sites-available/your-domain` 站点配置中，你可以这样设置一个反向代理，将请求转发到本地的 `3000` 端口的后端应用：

```
    server {
        listen 80;
        server_name your-domain.com;

        location / {
            # 将请求转发到 http://localhost:3000
            proxy_pass http://localhost:3000;
            # 传递客户端的原始 Host 头
            proxy_set_header Host $host;
            # 传递客户端的真实 IP 地址
            proxy_set_header X-Real-IP $remote_addr;
            # 传递客户端请求的代理路径
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            # 传递原始请求的协议 (HTTP 或 HTTPS)
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }

```

### <a class="reference-link" name="6.%20Nginx%20%E6%8A%A5%E9%94%99%E4%BA%86%E6%80%8E%E4%B9%88%E5%8A%9E%EF%BC%9F"></a>6. Nginx 报错了怎么办？

遇到 Nginx 错误时，可以按以下步骤排查：

```
    # 测试配置文件语法，通常能发现大部分配置问题
    sudo nginx -t

    # 查看 Nginx 错误日志，这是排查问题最重要的信息来源
    sudo tail -f /var/log/nginx/error.log

    # 查看 Nginx 访问日志，了解请求是否到达 Nginx 以及响应状态
    sudo tail -f /var/log/nginx/access.log

    # 查看系统日志中 Nginx 服务的相关信息
    sudo journalctl -u nginx -f

    # 验证端口绑定情况，检查是否有其他服务占用了 80 或 443 端口
    sudo netstat -tlnp | grep :80

```

### <a class="reference-link" name="7.%20Ubuntu%2022.04%E3%80%8124.04%20%E5%92%8C%2025.04%20%E5%AF%B9%20Nginx%20%E6%9C%89%E5%95%A5%E5%8C%BA%E5%88%AB%EF%BC%9F"></a>7. Ubuntu 22.04、24.04 和 25.04 对 Nginx 有啥区别？

主要区别体现在 Nginx 版本、支持周期以及一些功能特性上：

<div id="bkmrk-%E7%89%B9%E6%80%A7-ubuntu-22.04-ubun"><table><thead><tr><th>特性</th><th>Ubuntu 22.04</th><th>Ubuntu 24.04</th><th>Ubuntu 25.04</th></tr></thead><tbody><tr><td>Nginx 版本</td><td>1.18.0+</td><td>1.24.0+</td><td>1.26.0+</td></tr><tr><td>支持周期</td><td>2027 年</td><td>2029 年</td><td>2026 年</td></tr><tr><td>安全更新</td><td>标准</td><td>增强</td><td>最新</td></tr><tr><td>性能</td><td>良好</td><td>更好</td><td>最佳</td></tr><tr><td>新功能与特性</td><td>基础</td><td>高级</td><td>最前沿</td></tr></tbody></table>

</div>通常来说，`LTS` 版本（如 22.04 和 24.04）提供更长的支持周期和稳定性，更适合生产环境；而非 `LTS` 版本（如 25.04）则能让你更快地体验到 Nginx 的最新功能和性能改进。

## <a class="reference-link" name="%E6%80%BB%E7%BB%93%E4%B8%8E%E5%B1%95%E6%9C%9B"></a>总结与展望

朋友们，到这里，你已经成功在 Ubuntu 22.04、24.04 或 25.04 系统上安装并配置了一个功能完善的 Nginx Web 服务器。我们从最开始的安装，到配置防火墙，再到 Nginx 服务的管理，甚至连搭建 `Server Blocks`、安全加固和性能优化都一一攻克了。现在，你的 Web 服务器已经准备好，可以托管你的网站、充当反向代理、实现负载均衡，甚至处理高并发的应用请求了。

理解不同 Ubuntu 版本与 Nginx 的兼容性，也能帮助你为自己的项目做出明智的部署决策。通过我们一起学习的安全措施和性能调优选项，你的 Nginx 服务器在生产环境中将保持稳定、安全和高效。

这只是 Nginx 强大功能的冰山一角，Web 世界还有很多有趣的等着你去探索！

### <a class="reference-link" name="%E4%B8%8B%E4%B8%80%E6%AD%A5%EF%BC%8C%E4%BD%A0%E5%8F%AF%E4%BB%A5%E7%BB%A7%E7%BB%AD%E6%8E%A2%E7%B4%A2%EF%BC%9A"></a>下一步，你可以继续探索：

- **LEMP 栈**：搭建完整的应用环境，学习如何在 Ubuntu 上安装 `Linux`、`Nginx`、`MySQL` 和 `PHP` (`LEMP` 栈)。你可以参考：[How To Install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu](https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-22-04)
- **SSL/TLS 设置**：使用 `Let's Encrypt` 为你的网站添加 `HTTPS` 加密，让网站更安全、更受信任：[How To Secure Nginx with Let’s Encrypt on Ubuntu](https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-22-04)
- **反向代理进阶**：深入了解如何将 Nginx 配置为应用程序的反向代理，为你的 `Node.js`、`Python` 或其他后端服务提供强大的前端支持：[Nginx as a reverse proxy for your applications](https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-as-a-reverse-proxy-on-ubuntu-22-04)

不断学习，不断实践，你会在 DevOps 和 Web 开发的道路上越走越远，成为一名真正的“服务器魔法师”！

</body></html>

# python flask项目部署到服务器上,并制作docker镜像

### 部署python web项目到服务器（使用docker）

> **参考 : https://blog.51cto.com/fish/6023519**

#### (一)创建虚拟环境

    创建目录
    mkdir mytest
    cd mytest
    
    [root@python mytest]# pwd
    /root/mytest
    
    创建虚拟环境
    [root@python mytest]# python3 -m venv myvenv
    
    激活虚拟环境
    [root@python mytest]# source myvenv/bin/activate
    
    一旦激活虚拟环境后,将进入到该虚拟环境下的shell界面,如下:
    (myvenv) [root@python mytest]# 
    (myvenv) [root@python mytest]# ll
    total 16
    -rw-r--r--. 1 root root 222 Mar 31 11:14 demo.py
    -rw-r--r--. 1 root root 307 Mar 31 13:26 Dockerfile
    -rw-r--r--. 1 root root 282 Mar 31 13:38 gunicorn.conf.py
    drwxr-xr-x. 5 root root 100 Mar 31 11:45 myvenv
    -rw-r--r--. 1 root root 261 Mar 31 13:03 requirements.txt
    (myvenv) [root@python mytest]# 
    

#### (二)创建flask项目

> 在文件夹mytest下，创建一个demo.py启动文件

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        return 'hello docker & flask & 爱看书的小沐.'
    
    if __name__ == '__main__':
        app.run(host="0.0.0.0", debug=True)
    

> 在该环境下执行demo.py文件, 由于没有flask环境将报错

    (myvenv) [root@python mytest]# python demo.py
    ...
    
    安装flask
    (myvenv) [root@python mytest]# python install flask
    ...
    
    再次运行demo.py
    (myvenv) [root@python mytest]# python demo.py 
     * Serving Flask app 'demo' (lazy loading)
     * Environment: production
       WARNING: This is a development server. Do not use it in a production deployment.
       Use a production WSGI server instead.
     * Debug mode: on
     * Running on all addresses.
       WARNING: This is a development server. Do not use it in a production deployment.
     * Running on http://10.0.0.101:5000/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 128-311-800
     
    监听5000端口,可以正常跑起来
    

#### (三)安装 [gunicorn](https://so.csdn.net/so/search?q=gunicorn&spm=1001.2101.3001.7020) gevent, 提高性能

    (myvenv) [root@python mytest]# pip install gunicorn gevent flask
    
    在mytest目录下创建gunicorn.conf.py配置文件
    (myvenv) [root@python mytest]# vim gunicorn.conf.py
    
    文件内容如下:
    workers = 5    # 定义同时开启的处理请求的进程数量，根据网站流量适当调整
    worker_class = "gevent"   # 采用gevent库，支持异步处理请求，提高吞吐量
    bind = "0.0.0.0:5000"   #端口随便写，但是注意是否已经被占用。netstap -lntp
    

> 启动gunicorn,如下

    (myvenv) [root@python mytest]# gunicorn demo:app -c gunicorn.conf.py
    [2023-03-31 14:08:57 +0800] [58874] [INFO] Starting gunicorn 20.1.0
    [2023-03-31 14:08:57 +0800] [58874] [INFO] Listening at: http://0.0.0.0:3000 (58874)
    [2023-03-31 14:08:57 +0800] [58874] [INFO] Using worker: gevent
    [2023-03-31 14:08:57 +0800] [58877] [INFO] Booting worker with pid: 58877
    [2023-03-31 14:08:57 +0800] [58878] [INFO] Booting worker with pid: 58878
    [2023-03-31 14:08:57 +0800] [58879] [INFO] Booting worker with pid: 58879
    [2023-03-31 14:08:57 +0800] [58880] [INFO] Booting worker with pid: 58880
    [2023-03-31 14:08:57 +0800] [58881] [INFO] Booting worker with pid: 58881
    

#### (四)将项目部署到docker上

> **(1)** 执行如下命令, 生成python项目所依赖的包文件, 将其写入到requirements.txt文件中

    (myvenv) [root@python mytest]# pip freeze > requirements.txt
    (myvenv) [root@python mytest]# ll
    total 16
    -rw-r--r--. 1 root root 222 Mar 31 11:14 demo.py
    -rw-r--r--. 1 root root 282 Mar 31 13:38 gunicorn.conf.py
    drwxr-xr-x. 5 root root 100 Mar 31 11:45 myvenv
    drwxr-xr-x. 2 root root  69 Mar 31 14:08 __pycache__
    -rw-r--r--. 1 root root 261 Mar 31 13:03 requirements.txt
    (myvenv) [root@python mytest]# cat requirements.txt 
    click==8.0.4
    dataclasses==0.8
    Flask==2.0.3
    gevent==22.10.2
    greenlet==2.0.2
    gunicorn==20.1.0
    importlib-metadata==4.8.3
    itsdangerous==2.0.1
    Jinja2==3.0.3
    MarkupSafe==2.0.1
    typing_extensions==4.1.1
    Werkzeug==2.0.3
    zipp==3.6.0
    zope.event==4.6
    zope.interface==5.5.2
    (myvenv) [root@python mytest]# 
    

> **(2)** 创建Dockerfile文件, 用于构建自己的镜像

    (myvenv) [root@python mytest]# vim Dockerfile
    (myvenv) [root@python mytest]# cat Dockerfile
    FROM python:3.8
    
    WORKDIR /project/
    
    COPY requirements.txt ./
    RUN python -m pip install --upgrade pip
    RUN pip install --ignore-requires-python dataclasses==0.8
    RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
    
    #将当前所有文件拷贝到要制作的docker镜像中
    COPY . .
    
    CMD ["gunicorn", "demo:app", "-c", "./gunicorn.conf.py"]
    
    

> **(3)** 配置docker镜像加速地址

    [root@python mytest]#  mkdir -p /etc/docker
    [root@python mytest]#  tee /etc/docker/daemon.json <<-'EOF'
    {
        "registry-mirrors": [
    	"https://o6ul5754.mirror.aliyuncs.com",
    	"https://ung2thfc.mirror.aliyuncs.com",
    	"https://registry.docker-cn.com",
    	"http://hub-mirror.c.163.com",
    	"https://docker.mirrors.ustc.edu.cn"
    	]
    }
    EOF
    [root@python mytest]#  cat /etc/docker/daemon.json
    {
        "registry-mirrors": [
    	"https://o6ul5754.mirror.aliyuncs.com",
    	"https://ung2thfc.mirror.aliyuncs.com",
    	"https://registry.docker-cn.com",
    	"http://hub-mirror.c.163.com",
    	"https://docker.mirrors.ustc.edu.cn"
    	]
    }
    [root@python mytest]#  systemctl daemon-reload
    [root@python mytest]#  systemctl restart docker
    
    验证配置是否生效
    [root@python mytest]# docker info
    Client:
     Context:    default
     Debug Mode: false
     Plugins:
      buildx: Docker Buildx (Docker Inc.)
        Version:  v0.10.4
        Path:     /usr/libexec/docker/cli-plugins/docker-buildx
      compose: Docker Compose (Docker Inc.)
        Version:  v2.17.2
        Path:     /usr/libexec/docker/cli-plugins/docker-compose
      scan: Docker Scan (Docker Inc.)
        Version:  v0.23.0
        Path:     /usr/libexec/docker/cli-plugins/docker-scan
    
    Server:
     Containers: 5
      Running: 0
      Paused: 0
      Stopped: 5
     Images: 3
     Server Version: 23.0.2
     Storage Driver: overlay2
      Backing Filesystem: xfs
      Supports d_type: true
      Using metacopy: false
      Native Overlay Diff: true
      userxattr: false
     Logging Driver: json-file
     Cgroup Driver: cgroupfs
     Cgroup Version: 1
     Plugins:
      Volume: local
      Network: bridge host ipvlan macvlan null overlay
      Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
     Swarm: inactive
     Runtimes: io.containerd.runc.v2 runc
     Default Runtime: runc
     Init Binary: docker-init
     containerd version: 1e1ea6e986c6c86565bc33d52e34b81b3e2bc71f
     runc version: v1.1.4-0-g5fd4c4d
     init version: de40ad0
     Security Options:
      seccomp
       Profile: builtin
     Kernel Version: 3.10.0-957.el7.x86_64
     Operating System: CentOS Linux 7 (Core)
     OSType: linux
     Architecture: x86_64
     CPUs: 1
     Total Memory: 1.934GiB
     Name: python
     ID: IP2S:J2XT:35RB:KK7O:HFQ5:FMME:HNT2:LYFR:74GT:7CWE:GXGM:446B
     Docker Root Dir: /var/lib/docker
     Debug Mode: false
     Registry: https://index.docker.io/v1/
     Experimental: false
     Insecure Registries:
      127.0.0.0/8
     Registry Mirrors:
      https://o6ul5754.mirror.aliyuncs.com/
      https://ung2thfc.mirror.aliyuncs.com/
      https://registry.docker-cn.com/
      http://hub-mirror.c.163.com/
      https://docker.mirrors.ustc.edu.cn/
     Live Restore Enabled: false
    

> **(4)** 制作docker镜像

    [root@python mytest]# docker build -t myapp:1.0 .
    [+] Building 18.5s (12/12) FINISHED                                                                                                                                                               
     => [internal] load build definition from Dockerfile                                                                                                                                         0.0s
     => => transferring dockerfile: 406B                                                                                                                                                         0.0s
     => [internal] load .dockerignore                                                                                                                                                            0.0s
     => => transferring context: 2B                                                                                                                                                              0.0s
     => [internal] load metadata for docker.io/library/python:3.8                                                                                                                                0.2s
     => [1/7] FROM docker.io/library/python:3.8@sha256:4c4e6735f46e7727965d1523015874ab08f71377b3536b8789ee5742fc737059                                                                          0.0s
     => [internal] load build context                                                                                                                                                            0.2s
     => => transferring context: 370.95kB                                                                                                                                                        0.2s
     => CACHED [2/7] WORKDIR /project/                                                                                                                                                           0.0s
     => CACHED [3/7] COPY requirements.txt ./                                                                                                                                                    0.0s
     => CACHED [4/7] RUN python -m pip install --upgrade pip                                                                                                                                     0.0s
     => [5/7] RUN pip install --ignore-requires-python dataclasses==0.8                                                                                                                          2.3s
     => [6/7] RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple                                                                                                   12.5s
     => [7/7] COPY . .                                                                                                                                                                           2.2s 
     => exporting to image                                                                                                                                                                       1.2s 
     => => exporting layers                                                                                                                                                                      1.1s 
     => => writing image sha256:4afe28f18625b8bf5cdcb9785d158e9917561d1d6de1367e71bf4fa3d40fc407                                                                                                 0.0s 
     => => naming to docker.io/library/myapp:1.0                                                                                                                                                 0.0s 
    [root@python mytest]# docker images
    REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
    myapp         1.0       4afe28f18625   59 minutes ago   1.01GB
    hello-world   latest    feb5d9fea6a5   18 months ago    13.3kB
    

> **(5)** 运行该镜像成docker容器

    [root@python mytest]# docker run -d -p 5000:5000 myapp:1.0
    a91f1d816659e5abcd74a34d4bfc2a049a60c98d0a797a49202a7cc83bbc0778
    [root@python mytest]# 
    

> 浏览器访问 http://10.0.0.101:5000 页面可以正常访问并获取到数据

> **(6)** 如果修改代码, 需要重新制作该镜像文件, 例如修改demo.py文件如下

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        return 'hello docker 666'
    
    if __name__ == '__main__':
        app.run(host="0.0.0.0", debug=True, threaded=True)
    
    

> 同时修改端口5000为3000; 重新制作docker镜像文件

    [root@python mytest]# docker build -t myapp:1.1 .  # 这次打的标签tag版本为1.1
    [root@python mytest]# docker build -t myapp:1.1 .
    [+] Building 16.6s (12/12) FINISHED                                                                                                                                                               
     => [internal] load build definition from Dockerfile                                                                                                                                         0.0s
     => => transferring dockerfile: 406B                                                                                                                                                         0.0s
     => [internal] load .dockerignore                                                                                                                                                            0.0s
     => => transferring context: 2B                                                                                                                                                              0.0s
     => [internal] load metadata for docker.io/library/python:3.8                                                                                                                               15.2s
     => [1/7] FROM docker.io/library/python:3.8@sha256:4c4e6735f46e7727965d1523015874ab08f71377b3536b8789ee5742fc737059                                                                          0.0s
     => [internal] load build context                                                                                                                                                            0.2s
     => => transferring context: 370.93kB                                                                                                                                                        0.2s
     => CACHED [2/7] WORKDIR /project/                                                                                                                                                           0.0s
     => CACHED [3/7] COPY requirements.txt ./                                                                                                                                                    0.0s
     => CACHED [4/7] RUN python -m pip install --upgrade pip                                                                                                                                     0.0s
     => CACHED [5/7] RUN pip install --ignore-requires-python dataclasses==0.8                                                                                                                   0.0s
     => CACHED [6/7] RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple                                                                                             0.0s
     => [7/7] COPY . .                                                                                                                                                                           0.7s
     => exporting to image                                                                                                                                                                       0.5s
     => => exporting layers                                                                                                                                                                      0.5s
     => => writing image sha256:c7df86df2dd926af25bf4194e18abbd5af873ef25ba0ed5c5cbf686d8f2df62d                                                                                                 0.0s
     => => naming to docker.io/library/myapp:1.1                                                                                                                                                 0.0s
    [root@python mytest]# docker images
    REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
    myapp         1.1       c7df86df2dd9   7 seconds ago    1.01GB
    myapp         1.0       4afe28f18625   11 minutes ago   1.01GB
    hello-world   latest    feb5d9fea6a5   18 months ago    13.3kB
    [root@python mytest]# docker run -d -p 3000:3000 myapp:1.1
    254176fcad70aebde1bb80b120b7b1f715ea1c67ce2a4d3e949b5be1bec13abc
    [root@python mytest]#
    

> 再次访问 http://10.0.0.101:3000 已经正常访问

#### (五) 保存镜像文件到指定目录下

    查看当前镜像
    [root@python mytest]# docker images
    REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
    check_tools   1.4       1175ff06f5c3   21 hours ago    1.06GB
    check_tools   1.3       908c5ec78290   22 hours ago    1.04GB
    check_tools   1.2       c584b78ae39d   22 hours ago    1.04GB
    check_tools   1.1       770dd461a2cf   22 hours ago    1.04GB
    check_tools   1.0       2692e79d33a2   6 days ago      1.01GB
    myapp         1.1       c7df86df2dd9   7 days ago      1.01GB
    myapp         1.0       4afe28f18625   7 days ago      1.01GB
    hello-world   latest    feb5d9fea6a5   18 months ago   13.3kB
    hello-world   latest    feb5d9fea6a5   18 months ago   13.3kB
    
    保存镜像到指定目录下
    [root@python mytest]# docker save 1175ff06f5c3>/root/check_tools.tar #check_tools.tar为打包的文件
    
    查看保存的镜像文件 check_tools.tar
    [root@python mytest]# ll /root/
    total 1075124
    -rw-------.  1 root root       1650 Oct 22  2020 anaconda-ks.cfg
    -rw-r--r--.  1 root root 1083920896 Apr  6 16:10 check_tools.tar
    drwxr-xr-x.  4 root root        140 Apr  7 13:16 mytest
    drwxr-xr-x. 17  501  501       4096 Jan 12  2021 Python-3.6.4
    -rw-r--r--.  1 root root   16992824 Jan 12  2021 Python-3.6.4.tar.xz
    drwxr-xr-x.  2 root root         66 Jan 20  2021 test
    drwxr-xr-x.  3 root root         21 Jan 20  2021 virtualenv_1
    [root@python mytest]# 
    

#### (六) 在另一台主机上加载镜像文件

> 将上述步骤生成的`check_tools.tar`文件拷贝到另一台机器上进行加载

    [root@localhost ~]#  docker load < check_tools.tar        # check_tools.tar 为文件名称
    
    查看镜像
    [root@localhost ~]# docker images
    REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
    check_tools   1.4       1175ff06f5c3   21 hours ago    1.06GB
    [root@localhost ~]# 
    
    后台启动该镜像服务
    [root@localhost ~]# docker ps
    CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
    [root@localhost ~]# docker run -d -p 3000:3000 check_tools:1.4
    22870b5ee2f07c2faf85b9f29bbec078355b9dd510154abb6a2f299a0078792d
    [root@localhost ~]# docker ps
    CONTAINER ID   IMAGE             COMMAND                  CREATED          STATUS          PORTS                                       NAMES
    22870b5ee2f0   check_tools:1.4   "gunicorn check_tool…"   35 seconds ago   Up 34 seconds   0.0.0.0:3000->3000/tcp, :::3000->3000/tcp   flamboyant_keller
    [root@localhost ~]#  netstat -tunlp
    Active Internet connections (only servers)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
    tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      7037/sshd           
    tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      14811/docker-proxy  
    tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      7125/master         
    tcp6       0      0 :::22                   :::*                    LISTEN      7037/sshd           
    tcp6       0      0 :::3000                 :::*                    LISTEN      14815/docker-proxy  
    tcp6       0      0 ::1:25                  :::*                    LISTEN      7125/master         
    udp        0      0 127.0.0.1:323           0.0.0.0:*                           6325/chronyd        
    udp6       0      0 ::1:323                 :::*                                6325/chronyd        
    [root@localhost ~]# 
    

#### (七)逻辑卷映射

> 为避免每次修改代码后, 都要重新制作镜像文件, 采用逻辑卷映射: 将宿主机的某个目录映射到镜像文件中的某个目录, 以后只需要宿主机中的对应文件就可以

    逻辑卷映射 check_tool_data
    [root@python mytest]# docker run -p 3000:3000 -v check_tool_data:/project/ check_tools:1.7
    [2023-04-07 07:14:49 +0000] [1] [INFO] Starting gunicorn 20.1.0
    [2023-04-07 07:14:49 +0000] [1] [INFO] Listening at: http://0.0.0.0:3000 (1)
    [2023-04-07 07:14:49 +0000] [1] [INFO] Using worker: gevent
    [2023-04-07 07:14:49 +0000] [8] [INFO] Booting worker with pid: 8
    [2023-04-07 07:14:49 +0000] [9] [INFO] Booting worker with pid: 9
    [2023-04-07 07:14:49 +0000] [10] [INFO] Booting worker with pid: 10
    [2023-04-07 07:14:49 +0000] [11] [INFO] Booting worker with pid: 11
    [2023-04-07 07:14:50 +0000] [12] [INFO] Booting worker with pid: 12
    ^C[2023-04-07 07:17:02 +0000] [1] [INFO] Handling signal: int
    [2023-04-07 07:17:02 +0000] [8] [INFO] Worker exiting (pid: 8)
    [2023-04-07 07:17:02 +0000] [9] [INFO] Worker exiting (pid: 9)
    [2023-04-07 07:17:02 +0000] [12] [INFO] Worker exiting (pid: 12)
    [2023-04-07 07:17:02 +0000] [11] [INFO] Worker exiting (pid: 11)
    [2023-04-07 07:17:02 +0000] [10] [INFO] Worker exiting (pid: 10)
    [2023-04-07 07:17:03 +0000] [1] [INFO] Shutting down: Master
    
    查找逻辑卷位置
    [root@python mytest]# find / -name check_tool_data
    /var/lib/docker/volumes/check_tool_data
    [root@python mytest]# cd /var/lib/docker/volumes/check_tool_data
    [root@python _data]# ll
    total 24
    -rw-r--r--. 1 root root 7112 Apr  6 16:03 check_tools.py
    -rw-r--r--. 1 root root  222 Mar 31 11:14 demo.py
    -rw-r--r--. 1 root root  389 Apr  6 16:04 Dockerfile
    -rw-r--r--. 1 root root  281 Apr  6 15:27 gunicorn.conf.py
    drwxr-xr-x. 2 root root   71 Apr  7 15:14 json_file
    drwxr-xr-x. 5 root root  100 Apr  7 15:14 myvenv
    drwxr-xr-x. 2 root root   76 Apr  7 15:14 __pycache__
    -rw-r--r--. 1 root root  280 Apr  6 15:39 requirements.txt
    [root@python _data]# 
    

> 之后只需要修改 `/var/lib/docker/volumes/check_tool_data/check_tools.py`文件就可以了, 修改代码重新启动容器就可以加载到修改后的代码了
> 
>     [root@python mytest]# docker run -p 3000:3000 -v check_tool_data:/project/ check_tools:1.7
>     

您可

# Rustdesk中继服务器Docker安装

```shell
阿里服务器：
ID服务器：106.15.137.139:21116
中继服务器：106.15.137.139:21117
key：rnkeJJ7rqtUjoR82abrohV1UxcyMScgKY5zOICQXxm4=

腾讯服务器：
ID服务器：43.136.104.74:21116
中继服务器：43.136.104.74:21117
key：GGGTNhzko53SaVUm+wt+hhuctkXwz91b7U5DFCRZvuI=
```
### [要求](https://rustdesk.com/docs/zh-cn/self-host/rustdesk-server-oss/docker/#%e8%a6%81%e6%b1%82) 

您需要安装 Docker/Podman 才能将 rustdesk-server 作为 Docker 容器运行。如有疑问，请使用此[指南](https://docs.docker.com/engine/install)安装 Docker，以确保它是最新的！

确保在防火墙中打开这些端口：

*   `hbbs`:
    *   `21114` (TCP): 用于网页控制台，仅在 `Pro` 版本中可用。
    *   `21115` (TCP): 用于 NAT 类型测试。
    *   `21116` (TCP/UDP): **请注意 `21116` 应该同时为 TCP 和 UDP 启用。** `21116/UDP` 用于 ID 注册和心跳服务。`21116/TCP` 用于 TCP 打洞和连接服务。
    *   `21118` (TCP): 用于支持网页客户端。
*   `hbbr`:
    *   `21117` (TCP): 用于中继服务。
    *   `21119` (TCP): 用于支持网页客户端。

_如果您不需要网页客户端支持，可以禁用相应的端口 `21118`、`21119`。_

### Docker 示例 

    sudo docker image pull rustdesk/rustdesk-server
    sudo docker run --name hbbs -v ./data:/root -td --net=host --restart unless-stopped rustdesk/rustdesk-server hbbs
    sudo docker run --name hbbr -v ./data:/root -td --net=host --restart unless-stopped rustdesk/rustdesk-server hbbr

Note

`--net=host` 仅在 **Linux** 上有效，这使得 `hbbs`/`hbbr` 看到真实的传入 IP 地址而不是容器 IP (172.17.0.1)。 如果 `--net=host` 工作正常，则不使用 `-p` 选项。如果在 Windows 上，请省略 `sudo` 和 `--net=host`。

**如果您在您的平台上遇到连接问题，请移除 `--net=host`。**

**Note**

如果您无法使用 `-td` 看到日志，可以通过 `docker logs hbbs` 查看日志。或者您可以使用 `-it` 运行，`hbbs/hbbr` 不会作为守护进程模式运行。

### Docker Compose示例

要使用这里描述的 `docker-compose.yml` 运行 Docker 文件，您需要安装 [Docker Compose](https://docs.docker.com/compose/)。

```shell
networks:
  rustdesk-net:
    external: false

services:
  hbbs:
    container_name: hbbs
    ports:
      - 21115:21115
      - 21116:21116 # 自定义 hbbs 映射端口
      - 21116:21116/udp # 自定义 hbbs 映射端口
    image: docker.1ms.run/rustdesk/rustdesk-server:latest
    command: hbbs
    volumes:
      - ./hbbs_data:/root # 自定义挂载目录
    networks:
      - rustdesk-net
    depends_on:
      - hbbr
    restart: unless-stopped
    deploy:
      resources:
        limits:
          memory: 64M

  hbbr:
    container_name: hbbr
    ports:
      - 21117:21117 # 自定义 hbbr 映射端口
    image: docker.1ms.run/rustdesk/rustdesk-server:latest
    command: hbbr
    volumes:
      - ./hbbr_data:/root # 自定义挂载目录
    networks:
      - rustdesk-net
    restart: unless-stopped
    deploy:
      resources:
        limits:
          memory: 64M
```

# ubuntu+Windows双系统默认引导顺序

## 在 Ubuntu 中修改引导顺序
打开ubuntu系统以后，我们打开超级终端，输入以下命令
```shell
sudo gedit /etc/default/grub
```

我装了双系统，Windows的选择在最下面，所以是4（具体数字看你显示，上图标注了0开始）
![](http://showdoc.bakeding.site/server/index.php?s=/api/attachment/visitFile&sign=5950bf7b1e20e940fcda22463fef76f6)

修改完成后要重新编译引导文件生效。
```shell
sudo update-grub
```

## 在 Windows 中添加 Ubuntu 引导项

以管理员身份打开 PowerShell，执行：

```shell
bcdedit /set "{bootmgr}" path \EFI\ubuntu\grubx64.efi
```

重启后应出现 GRUB 菜单。

# tailscale 自建服务器

为什么是VPN？
--------

[前面](https://zhuanlan.zhihu.com/p/689461755)讲过，我企图打通各个住所和学校的内网。列位要问了，你不是搞过[FRP内网穿透](https://zhuanlan.zhihu.com/p/687477877)吗，为啥还要VPN？我个人的理解是：**FRP侧重于服务，依托于开放的端口；VPN侧重于互连，依托于C/S架构和IP**，对比于下表。可见，要打通各个内网，必须使用基于VPN的技术才行。

| 对比项 | FRP | VPN |
| --- | --- | --- |
| 开放端口数 | 随服务数增加 | 很少 |
| 主要应用 | 对外提供服务，网页服务较多 | 对内提供连通 |
| 穿透方向 | 单向 | 双向（通过路由） |
| 安全性 | 一般 | 强 |
| IP级互连 | 不支持 | 支持 |
| 额外的客户端 | 不需要 | 一般需要 |
| 部署难度 | 容易 | 困难 |

用哪个VPN？
-------

关于主流VPN技术，下面这篇文章总结的挺好。

[anonymous：WireGuard到底好在哪？](https://zhuanlan.zhihu.com/p/404402933) 

我斗胆再一句话总结下：`PPTP`不安全；`OpenVPN`针对`IPSec/L2TP`做了减法；`WireGuard`针对`OpenVPN`又做了减法，**性能更高，还支持了去中心化。**

可见，`WireGuard`是目前**最先进**的VPN技术，已被引入Linux内核，必须选她！

> 还有个原因，群晖的VPN服务端都被阉割了，自己装套件起`OpenVPN`也不行；威联通的`OpenVPN`服务端可以，但静态路由设置时总是出错。

为什么是`Headscale`？
----------------

`WireGuard`目前只是一个内核级别的模块，想要配置好裸的`WireGuard`，低代码是别想了，那么多对端秘钥，增、删节点都需要改动所有节点的配置，想一想就头疼！

> 表扬威联通，已经支持图形化界面的`WireGuard`服务器和客户端。

基于`WireGuard`的上层应用，目前比较成熟的有`Tailscale`和`Netmaker`。`Tailscale` 是在用户态实现了 `WireGuard` 协议；`Netmaker` 直接使用了内核态的`WireGuard`，理论上性能更高，但目前缺乏中继机制（类似FRP），应用场景受限。`Headscale`是`Tailscale`的开源实现，适合私有部署，就选她了！

本文动机
----

知乎上介绍`Headscale`的很少；找遍全网，也很少有低代码、快速部署`Headscale`的文章，能讲清楚原理和为什么这样配置的就更少了。

仍然要感谢一些博主，虽然不讲原理，但内容确实丰富，给我一定启发（其实是偷懒不用去看文档了），比如下面这个。

[Tailscale玩法之内网穿透、异地组网、全隧道模式、纯IP的双栈DERP搭建、Headscale协调服务器搭建，用一期搞定，看一看不亏吧？](https//www.bilibili.com/video/BV1Wh411A73b/%3Fshare_source%3Dcopy_web%26vd_source%3Df641fc9bab269a29e49838117c00cf36 "Tailscale玩法之内网穿透、异地组网、全隧道模式、纯IP的双栈DERP搭建、Headscale协调服务器搭建，用一期搞定，看一看不亏吧？")

我在群晖和威联通的NAS上都用`docker-compose`部署成功了，必须向大家汇报下，希望能帮助更多非专业领域的“私有云折腾师”。

Headscale搭建
-----------

### 架构介绍

主节点（我自己定义的概念）的网络拓扑如下图所示。其他节点与之类似，不包含服务端及其UI。

![](https://pic3.zhimg.com/v2-9d3f34ee49fba7a2c49609653ad7c0d6_1440w.jpg)

主节点网络拓扑

**服务端（server）**，又叫协调服务器。负责`WireGuard`节点的公钥交换、虚拟IP分配、路由转发的公开和访问控制。

**客户端（client）**，即`WireGuard`节点。目前仍然使用的是`Tailscale`的开源客户端，采用`go`语言编写，在用户空间实现`WireGuard`。

**中继端（derp）**，是P2P连接时NAT穿透的保底方案。DERP（Detoured Encrypted Routing Protocol）是`Tailscale`自研的协议，运行在 HTTP 之上 ，根据目的公钥来中继加密的流量。中继端同时支持DERP和STUN。

> 关于NAT穿透的原理，可以参考下面这篇。

[NAT穿透arthurchiao.art/blog/how-nat-traversal-works-zh/](https://link.zhihu.com/?target=https%3A//arthurchiao.art/blog/how-nat-traversal-works-zh/)

可见，服务端负责控制，中继端负责数据通路，客户端发起/接受连接，是可以部署在不同的服务器上的。这里我们资源有限，把他们都部署在一个NAS里，还需要使用**反向代理（`lucky`）**以“零代码”支持带SSL证书的HTTPS访问；为了“低代码”配置服务端，我们给她再加一个**服务端控制界面（webui，以下简称UI端）**，齐活。

关于客户端，其实有两个作用。一是做为`WireGuard`的**节点**连到大内网里。

> 这时，为了减少路由的层级，其容器的网络类型一般设为host。

二是通过Unix的进程间通信（sock）**为中继端提供用户认证**，防止中继端被他人使用。

> 通过把客户端和中继端的/var/run/headscale链接在一起来实现。这时，其容器的网络类型最好设为bridge。

如何选择容器网络类型，可以参考下面的公式。

    假设，中继端部署在服务器A上，负责VPN路由的是服务器B。
    if(A == B)
      在A上部署客户端，容器网络使用host。
    else {
      在A上部署客户端，容器网络使用bridge或host都行。
      在B上部署客户端；如果使用容器，其网络使用host。// 例如，OpenWRT上可以直接部署。
    }

> 关于自定义的容器子网，可以参考下面这篇文章。

[IC民工：NAS添加静态路由失效的主要原因：容器子网滥用](https://zhuanlan.zhihu.com/p/688222318) 

我把这些容器都部署在一个NAS上，所以用host。相关的端口如下表，使用了基于子域名的`lucky`反向代理后，只需要对公网（别忘了在路由器上做端口映射）暴露一个STUN的`UDP3478`端口（新增）和一个`lucky`反向代理的端口（例如`8080`，已有）。相比FRP，美极了。

|  | 服务端 | UI端 | 中继端DERP | 中继端STUN |
| --- | --- | --- | --- | --- |
| 端口类型 | TCP | TCP | TCP | UDP |
| 容器侧端口 | 8080 | 7070 | 6060 | 3478 |
| NAS侧端口 | 58080 | 57070 | 56060 | 3478 |
| HTTPS反向代理 | 需要 | 需要 | 需要 | 不需要 |

### 容器编排

直接给出带注释的四合一`docker-compose.yaml`，全网罕见。

```shell
version: '3.9'

networks: # 定义编排容器的子网
  private:
    driver: bridge
    ipam:
      config:
        - subnet: 172.28.200.0/24

services:
  server: # 服务端
    image: headscale/headscale
    container_name: headscale-server
    networks:
      - private
    volumes:
      - ./headscale/config:/etc/headscale # 提前放好config.yaml和derp.yaml
      - ./headscale/data:/var/lib/headscale
      - ./headscale/run:/var/run/headscale
      - /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime:ro # 使用NAS的时间
    ports:
      - "58080:8080" # listen port
    command: serve # v0.22及以前的版本需要使用headscale serve
    restart: unless-stopped
    depends_on:
      - derp

  webui: # UI端
    image: ghcr.io/gurucomputing/headscale-ui
    container_name: headscale-ui
    networks:
      - private
    environment:
      HTTP_PORT: 7070
    ports:
      - "57070:7070" 
    volumes:
      - /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime:ro
    restart: unless-stopped

  derp: # 中继端
    image: fredliang/derper
    container_name: headscale-derp
    networks:
      - private
    environment:
      DERP_DOMAIN: derp.bakeding.site # 替换为自己的域名
      DERP_ADDR: :6060 # 注意，前面有个英文冒号
      DERP_CERT_MODE: letsencrypt # 使用了lucky做反向代理，理论上不需要设置，但我还没试过。
      DERP_VERIFY_CLIENTS: true # 还用client做认证时，配置为true
    ports:
      - "56060:6060" # derp port, TCP
      - "3478:3478/udp"  # STUN port, UDP
    volumes:
      - ./tailscale:/var/run/tailscale
      - /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime:ro
    restart: unless-stopped
    depends_on:
      - client

  client: # 客户端
    image: tailscale/tailscale
    container_name: headscale-client
    network_mode: "host" # 用做连接各子网的客户端时，这样最简单
    privileged: true
    environment:
      TS_EXTRA_ARGS: --netfilter-mode = off # 默认不开启路由转发，更灵活
    volumes:
      - ./tailscale:/var/run/tailscale # 要在NAS上和derp共享同一个目录
      - /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime:ro
      - /var/lib:/var/lib
      - /dev/net/tun:/dev/net/tun
    cap_add:
      - net_admin
      - sys_module
    command: tailscaled
    restart: unless-stopped
```

注意，要提前配置好`config.yaml`和`derp.yaml`。可以去GitHUB的代码仓，下载`config-example.yaml`和`derp-example.yaml`，修改好内容（见下文）并重命名。

[headscale代码仓](https//github.com/juanfont/headscale/tree/main)

> 我用的是`latest`映像，当前对应源码的版本是`v0.23.0-alpha5`。配置文件如果报错，可以去搜一下`Issues`，一般都有答案。

另外，只需要把`docker-compose.yaml`中`server`和`webui`的部分注释掉，就可以部署在其他节点。如果不想增加中继端，也可以把`derp`的部分注释掉。

### 服务端配置

`config.yaml`中修改的地方如下。

*   `server_url`要改成反向代理后的网址。
*   把`urls`下面的网址注释掉，不使用官方的中继端。
*   增加`derp.yaml`的位置，指定自己搭建的中继端。
*   注意各端口要和`docker-compose.yaml`中的对应。

```shell
    server_url: https://tailscale.bakeding.site
    listen_addr: 0.0.0.0:8080
    # Address to listen to /metrics, you may want to keep this endpoint private to your internal network
    metrics_listen_addr: 0.0.0.0:9090
    grpc_listen_addr: 0.0.0.0:50443 # 看起来没啥用
    ip_prefixes:
      100.100.0.0/16
      # List of externally available DERP maps encoded in JSON
      urls:
        #- https://controlplane.tailscale.com/derpmap/default
    
      # Locally available DERP map files encoded in YAML
      paths:
        - /etc/headscale/derp.yaml
```

`derp.yaml`如下，这里我添加了两个中继端。

```shell
# If you plan to somehow use headscale, please deploy your own DERP infra: https://tailscale.com/kb/1118/custom-derp-servers/
regions:
  901:
    regionid: 901
    regioncode: huoyan
    regionname: tencent
    nodes:
      - name: tencent-derp
        regionid: 901
        hostname: derp.bakeding.site
        stunport: 3478
        stunonly: false
        derpport: 56060

      902:
        regionid: 902
        regioncode: hk
        regionname: Hongkong Telecom
        nodes:        
          - name: shelter2-derp
            regionid: 902
            hostname: derp.mirror.example.com
            stunport: 3478
            stunonly: false
            derpport: 56060
```

### 反向代理配置
headscale-server和derp正常进行反代就行了，ui端因为跨域的原因，需要在同一个域里。如您按照本文提供的内容进行创建的话，那么你可以直接使用此nginx配置，否则请自行修改相应端口。
```shell
server {
	#监听443端口
    listen 443 ssl;
    #你的域名
    server_name tailscale.bakeding.site; 
	access_log /var/log/nginx/tailscale443.log;
    #ssl证书的pem文件路径
    ssl_certificate  /www/cert/tailscale.bakeding.site_bundle.pem;
    #ssl证书的key文件路径
    ssl_certificate_key /www/cert/tailscale.bakeding.site.key;
	
    location ^~ / {
		proxy_pass http://127.0.0.1:58080; 
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr; 
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
		proxy_set_header REMOTE-HOST $remote_addr; 
		proxy_set_header Upgrade $http_upgrade; 
		proxy_set_header Connection "upgrade"; 
		proxy_set_header X-Forwarded-Proto $scheme; 
		proxy_http_version 1.1; 
		add_header X-Cache $upstream_cache_status; 
		add_header Strict-Transport-Security "max-age=31536000"; 
		add_header Cache-Control no-cache; 
	}

	location ^~ /web {
		proxy_pass http://127.0.0.1:57070; 
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr; 
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
		proxy_set_header REMOTE-HOST $remote_addr; 
		proxy_set_header Upgrade $http_upgrade; 
		proxy_set_header Connection "upgrade"; 
		proxy_set_header X-Forwarded-Proto $scheme; 
		proxy_http_version 1.1; 
		add_header X-Cache $upstream_cache_status; 
		add_header Strict-Transport-Security "max-age=31536000"; 
		add_header Cache-Control no-cache; 
	}

}
server {
	listen       80;	#监听80端口
	listen  [::]:80;
	server_name  tailscale.bakeding.site;		#也可以填写自己注册的域名
	access_log /var/log/nginx/default.log;

	location ^~ / {
		proxy_pass http://127.0.0.1:56060; 
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr; 
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
		proxy_set_header REMOTE-HOST $remote_addr; 
		proxy_set_header Upgrade $http_upgrade; 
		proxy_set_header Connection "upgrade"; 
		proxy_set_header X-Forwarded-Proto $scheme; 
		proxy_http_version 1.1; 
		add_header X-Cache $upstream_cache_status; 
		add_header Strict-Transport-Security "max-age=31536000"; 
	}

	location ^~ /web {
		proxy_pass http://127.0.0.1:57070; 
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr; 
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
		proxy_set_header REMOTE-HOST $remote_addr; 
		proxy_set_header Upgrade $http_upgrade; 
		proxy_set_header Connection "upgrade"; 
		proxy_set_header X-Forwarded-Proto $scheme; 
		proxy_http_version 1.1; 
		add_header X-Cache $upstream_cache_status; 
		add_header Strict-Transport-Security "max-age=31536000"; 
		add_header Cache-Control no-cache; 
	}

  
    #error_page  404              /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;		#错误页面设置
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

server {
	#监听443端口
    listen 443 ssl;
    #你的域名
    server_name derp.bakeding.site; 
	access_log /var/log/nginx/derp443.log;
    #ssl证书的pem文件路径
    ssl_certificate  /www/cert/derp.bakeding.site_bundle.pem;
    #ssl证书的key文件路径
    ssl_certificate_key /www/cert/derp.bakeding.site.key;
	
    location ^~ / {
		proxy_pass http://127.0.0.1:56060; 
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr; 
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
		proxy_set_header REMOTE-HOST $remote_addr; 
		proxy_set_header Upgrade $http_upgrade; 
		proxy_set_header Connection "upgrade"; 
		proxy_set_header X-Forwarded-Proto $scheme; 
		proxy_http_version 1.1; 
		add_header X-Cache $upstream_cache_status; 
		add_header Strict-Transport-Security "max-age=31536000"; 
	}

}
server {
	listen       80;	#监听80端口
	listen  [::]:80;
	server_name  tailscale.bakeding.site;		#也可以填写自己注册的域名
	access_log /var/log/nginx/default.log;

	location ^~ / {
		proxy_pass http://127.0.0.1:56060; 
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr; 
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
		proxy_set_header REMOTE-HOST $remote_addr; 
		proxy_set_header Upgrade $http_upgrade; 
		proxy_set_header Connection "upgrade"; 
		proxy_set_header X-Forwarded-Proto $scheme; 
		proxy_http_version 1.1; 
		add_header X-Cache $upstream_cache_status; 
		add_header Strict-Transport-Security "max-age=31536000"; 
	}

  
    #error_page  404              /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;		#错误页面设置
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
```



### 服务端操作（步骤1）

其实服务端支持很多命令行操作，但我们追求“低代码”，只需要用命令行生成一个API Key，剩下的工作在UI端点鼠标就行了。

进入容器，执行命令，**把生成的API Key记录下来**：ynREpBS.UduOZ_Dwxu1WRreh6vMKvUsiNwvefz_n

    $ headscale apikeys create -e 9999d

其中，`-e`后面指定的是过期时间，这里我指定9999天，27年后看能否有人攻破。

> 也可以在宿主机上执行，前面加`sudo docker exec -it`即可，不会的可以练练。

### UI端操作（步骤2）

1.  打开UI的URL，本例为`https://tailscale.bakeding.site/web`。

2\. 进入“Settings”。

3\. 添加“Headscale URL”，本例为`https://tailscale.bakeding.site`。

4\. 把服务端生成的Key添加到“Headscale API Key”。

5\. 点击“Test Server Settings”，出现绿色对号后UI端就可以接管服务端了，如下图所示。

![](https://pic3.zhimg.com/v2-f206b39366e4dc4f99c81ade5cabceac_1440w.jpg)

UI端添加API Key

6\. 进入“User View”，点击“+New User”，添加一个用户。

![](https://pic4.zhimg.com/v2-ebf6deda81726c4ea94bf82be5a94077_1440w.jpg)

UI端添加用户

7\. 为该用户生成一个Preauth Key，供客户端连接使用。为了便捷性，最好设置为“Reusable”，并“Active”，如下图。

![](https://pic4.zhimg.com/v2-5a765f6b989dcf1b895c9039207a986f_1440w.jpg)

UI端添加Preauth Key

> 连接的密钥设置比较灵活，有两种方法。一种是上面这种：在服务端生成Preauth Key（1个共享或多个独立），客户端连接时指定，成功后在“Device View”里就能看到各个节点。另一种是在客户端连接时生成，在UI端的“Device View”里手动添加秘钥、注册节点。我这么懒惰，当然共享1个Preauth Key。

### 客户端操作（步骤3）

1.  进入各客户端的容器，执行命令。

```shell
   tailscale up --netfilter-mode=off \
                 --accept-routes \
                 --advertise-routes=192.168.2.0/24 \
                 --login-server=https://tailscale.bakeding.site \
                 --auth-key=c5765d7426fe55c005ffda74419ec38f9a32fd770fa13199
```

*   `--accept-routes`代表接受其他节点的路由指示。
*   `--advertise-routes`指定本节点对其他节点的路由建议，即哪个网段走VPN到本节点。一般是本节点的内网网段。
*   `--login-server`指定服务端的URL。
*   `--auth-key`指定在UI端生成的Preauth Key。

2\. 打开UI端网页，进入“Device View”，把各节点的“Device Routes”设置为“active”，如下图。

> 这里还可以看到各个节点分配的VPN IP地址。

![](https://picx.zhimg.com/v2-e701e612c541ac66c6183b9bad75f1d7_1440w.jpg)

UI端开启Devic Routes

### NAS配置（步骤4）

要在NAS上开启路由转发，把VPN路由过来的包转发到内网。

1.  通过ssh登录到NAS，执行命令。

    $ ip addr

2\. 找到NAS的内网IP地址所对应的虚拟网卡名，我这里是`ovs_eth0`；找到VPN地址所对应的网卡名，我这里是`tailscale0`。

3\. 执行命令：启用IPv4转发功能；防火墙配置了两个网络接口（`ovs_eth0`和`tailscale0`）的数据包转发规则，并执行网络地址转换（NAT）操作。使能了VPN子网和内网的双向互访。

```shell
   sudo iptables -I FORWARD -i ovs_eth0 -j ACCEPT
   sudo iptables -I FORWARD -o ovs_eth0 -j ACCEPT
   sudo iptables -t nat -I POSTROUTING -o ovs_eth0 -j MASQUERADE
   sudo iptables -I FORWARD -i tailscale0 -j ACCEPT
   sudo iptables -I FORWARD -o tailscale0 -j ACCEPT
   sudo iptables -t nat -I POSTROUTING -o tailscale0 -j MASQUERADE
   sudo sysctl -w net.ipv4.ip_forward=1
```

4\. 最后，把它们加到群晖的“计划任务”，开机触发启动。

*   去掉所有`sudo`，以root执行。
*   为了保证VPN相关的容器先启动，最上面最好加个`sleep 1m`。

### 主路由配置（步骤5）

为了让本节点内网的其他地址也能通过VPN访问其他节点的内网，需要在主路由上添加静态路由，例如下表。

| 描述 | 目的地址 | 子网掩码 | 下一跳地址 | 出接口 |
| --- | --- | --- | --- | --- |
| 访问VPN节点 | 100.100.0.0 | 255.255.0.0 | 本节点NAS地址 | LAN |
| 访问其他节点的内网 | 其他节点的内网网段 | 其他节点的内网掩码 | 本节点NAS地址 | LAN |

经过ping测试，大功告成！

参考文章
[Tailscale/Headscale自建异地组网 ](https://www.dhao2001.com/2025/01/11/headscale-self-hosted-quick-start/ "Tailscale/Headscale自建异地组网 ")
[Tailscale+Headscale+自建Derp踩坑记录](https://iyyh.net/posts/tailscale-headscale-self-hosted-derp-troubleshooting-record "Tailscale+Headscale+自建Derp踩坑记录")
**已验证：**[自建Tailscale的 DERP 中继教程](https://ouximei.com/2025/01/24/%e8%87%aa%e5%bb%batailscale%e7%9a%84-derp-%e4%b8%ad%e7%bb%a7%e6%95%99%e7%a8%8b/ "自建Tailscale的 DERP 中继教程")

# tailscale客户端连接headscale

## 阿里服务器：
https://tailscale.bakeding.site

** Headscale `API Key`：**
```shell
vrSvmc5.TU76cARTlr0Ifv2kdDaBvuthY1GuqEi0
```

** eason user `Preauth Keys`： **
```shell
6aa4e048254831ebae24254359a04bff94b22e6b93f56958
```

** 运行命令：**
```shell
tailscale up -login-server https://tailscale.bakeding.site -authkey 6aa4e048254831ebae24254359a04bff94b22e6b93f56958 -accept-dns=false -accept-routes --advertise-exit-node --reset
tailscale up -login-server https://tailscale.bakeding.site -authkey 6aa4e048254831ebae24254359a04bff94b22e6b93f56958 -accept-dns=false -accept-routes  --advertise-routes=10.8.0.0/24 --advertise-exit-node --reset
```

## 腾讯服务器：
https://tailscale.bakeding.site

** Headscale `API Key`：**
```shell
ynREpBS.UduOZ_Dwxu1WRreh6vMKvUsiNwvefz_n
```

** eason user `Preauth Keys`：**
```shell
c5765d7426fe55c005ffda74419ec38f9a32fd770fa13199 
```

** 运行命令：**
```shell
tailscale up -login-server https://tailscale.bakeding.site -authkey c5765d7426fe55c005ffda74419ec38f9a32fd770fa13199 -accept-dns=false -accept-routes  --advertise-exit-node --reset
# 或者
tailscale up -login-server https://tailscale.bakeding.site -authkey c5765d7426fe55c005ffda74419ec38f9a32fd770fa13199 -accept-dns=false -accept-routes  --advertise-routes=10.9.0.0/24 --advertise-exit-node --reset
```
## 常用命令 
```shell
tailscale netcheck 
taiscale ping 100.100.0.1
tailscale status
tailscale switch eason
tailscale switch bakeding@126.com
```

# wireguard配置

# wg-easy 镜像docker安装
`docker-compose.yml`
```shell
services:
  wg-easy:
    container_name: wg-easy
    image: ghcr.io/wg-easy/wg-easy
    network_mode: bridge
    environment:
      - LANG=chs # or en, de ...
      - WG_HOST=43.136.104.74 #替换自己的服务器ip
      - PASSWORD=123456 # WebUI 登录密码（明文即可，容器会自动 bcrypt）
      #- PASSWORD_HASH=$$2a$$12$$S5L7nVgk6I7O/tdVLyVH0.QmD89RHJdKgHL8ayXOiGYwwFa4UmONC #PASSWORD和这一个密码用其中一个
      - LANG=chs# 可选：中文界面
      - WG_DEFAULT_DNS=192.168.2.1,114.114.114.114,8.8.8.8,8.8.4.4
      - PORT=51820 #可更改
      - WG_DEFAULT_ADDRESS=10.9.0.x
      - WG_PORT=51821 # 可选：自定义 WireGuard 端口
      - WG_PRE_UP = iptables -t nat -F; iptables -F;  # Flush all rules
      #- WG_POST_UP=iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
      #- WG_POST_DOWN=iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
      - WG_ALLOWED_IPS=114.114.114.114,8.8.8.8,8.8.4.4,192.168.2.0/24,10.9.0.0/24
      
      - UI_TRAFFIC_STATS=true
      - UI_CHART_TYPE=3 # (0 Charts disabled, 1 # Line chart, 2 # Area chart, 3 # Bar chart)
      # - WG_ENABLE_ONE_TIME_LINKS=true
      - UI_ENABLE_SORT_CLIENTS=true
      # - WG_ENABLE_EXPIRES_TIME=true
    volumes:
      - /home/ubuntu/work/wireguard:/etc/wireguard
    ports:
      - 51820:51820/tcp
      - 51821:51821/udp
    cap_add:
      - NET_ADMIN
      - SYS_MODULE
    sysctls:
      - net.ipv4.conf.all.src_valid_mark=1
      - net.ipv4.ip_forward=1
    restart: unless-stopped
```

### 必须知道的事情
**PASSWORD_HASH**
```shell
PASSWORD_HASH=$$2a$$12$$31H.ZEl74tEF98shuIWWxe2PTsljr3vEMRfU7HL8dPvNJTImcUgRq
```
这是密码为123456的哈希值，参见 [How_to_generate_an_bcrypt_hash.md](https://github.com/wg-easy/wg-easy/blob/master/How_to_generate_an_bcrypt_hash.md "How_to_generate_an_bcrypt_hash.md") 来了解如何获取这个哈希值，当你登录到`wg-easy`配置web界面时，`123456`将是你的密码。但现在的方法有一点问题，所以可以用以下命令代替：

```shell
sudo docker run -it ghcr.io/wg-easy/wg-easy /app/wgpw.sh 123456
```

如果上述命令的输出是：
```shell
PASSWORD_HASH='$2a$12$31H.ZEl74tEF98shuIWWxe2PTsljr3vEMRfU7HL8dPvNJTImcUgRq'
```
因为我们使用的是`docker-compose.yaml`文件，需要将每个`$`符号替换为两个`$$`符号。所以在yaml中的`PASSWORD_HASH`应为：
```shell
PASSWORD_HASH=$$2a$$12$$31H.ZEl74tEF98shuIWWxe2PTsljr3vEMRfU7HL8dPvNJTImcUgRq
```
记得用一个更强的密码替换简单的`123456`。

关于我们使用的IP和IP范围的注释：
```shell
192.168.2.1 主机网络网关，请改为你的主机网络网关。
192.168.2.0/24 主机网络IP范围，请同样改为你的主机网络IP范围。
10.9.0.x 你的虚拟网络IP范围，除非你偏好其他的IP范围，否则不需要更改。
10.9.0.0/24 由 10.9.0.x 设定的虚拟网络IP范围。
```

# 手动安装

WireGuard是什么？
-------------

维基百科是这样描述的：

*   WireGuard是一种实现加密虚拟专用网络(VPN) 的通信协议和免费开源软件，其设计目标是易于使用、高速性能和低攻击面；
*   它旨在比IPsec和OpenVPN这两种常见的隧道协议具有更好的性能和更强大的功能；  
    WireGuard 协议通过UDP传递流量。

通过描述，我们知道了wireguard其实就是一个FAST（速度快）、MODERN（流行）、SECURE （安全）的VPN TUNNEL（VPN隧道）。

安装前提条件
------

1.  需要有公网的ip地址（这些地址可以直接在腾讯云、阿里云等厂商购买）；
2.  如果Linux内核版本<5.6，可能需要首先更新内核（本文下面有内核升级教程）；
3.  `WireGuard` 的安装和使用条件非常苛刻，对内核版本要求极高，不仅如此，在不同的系统中，内核，内核源码包，内核头文件必须存在且这三者版本要一致。所以一般不建议在生成环境中安装，除非你对自己的操作很有把握。`Red Hat`、`CentOS`、`Fedora` 等系统的内核，内核源码包，内核头文件包名分别为 `kernel`、`kernel-devel`、`kernel-headers`，`Debian`、`Ubuntu` 等系统的内核，内核源码包，内核头文件包名分别为 `kernel`、`linux-headers`。

如果这三者任一条件不满足的话，则无法测试和安装 `Wiregurad` !

目前 `WireGuard` 已经被合并到 `Linux 5.6` 内核中了，如果你的内核版本 >= `5.6`，就可以用上原生的 `WireGuard` 了，只需要安装 `wireguard-tools` 即可。例如，对于 `Ubuntu 20.04` 来说，它的内核版本是 `5.4`，虽然小于 `5.6`，但经过我的测试发现它已经将 `WireGuard` 合并到了内核中，我们只需要安装 `wireguard-tools` 即可。

安装WireGuard
-----------

**教程中使用的系统为`Ubuntu 24.04`。**

第0步：切换到root用户

    sudo su

第一步：开启内核转发：

    echo 1 > /proc/sys/net/ipv4/ip_forward
    echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
    sysctl -p

第二步：安装WireGuard

    apt update
    apt install wireguard -y
    apt install resolvconf -y

第三步：验证是否安装成功

    wg --version

正常来说应该可以看到类似下面的输出：

    wireguard-tools v1.0.20210914 - https://git.zx2c4.com/wireguard-tools/

另外一种验证方式：

    modprobe wireguard && lsmod | grep wireguard

输出如下：

    wireguard              86016  0
    curve25519_x86_64      36864  1 wireguard
    libchacha20poly1305    16384  1 wireguard
    libblake2s             16384  1 wireguard
    ip6_udp_tunnel         16384  1 wireguard
    udp_tunnel             24576  1 wireguard
    libcurve25519_generic    49152  2 curve25519_x86_64,wireguard

配置WireGuard
-----------

    cd /etc/wireguard

### 服务端配置

1、生成服务器私钥并将其保存在`/etc/wireguard/server_private.key`：

    wg genkey | sudo tee /etc/wireguard/server_private.key

输出如下：

    UOO//MO2GCC+5hHOz91YCP60/Zv/cnSskEH2j4eRPXo=

2、生成服务器公钥并将其保存在`/etc/wireguard/server_public.key`：

    cat /etc/wireguard/server_private.key | wg pubkey | sudo tee /etc/wireguard/server_public.key

输出如下：

    W+l7Uapd98bsNhN1g3Hs4iTCfKzcV03KNwhDPFgzqR4=

3、查看可用的服务器网络接口并验证主接口的详细信息

    ip a

输出如下：

    1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
        link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
        inet 127.0.0.1/8 scope host lo
           valid_lft forever preferred_lft forever
        inet6 ::1/128 scope host noprefixroute 
           valid_lft forever preferred_lft forever
    2: enp1s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
        link/ether 56:00:04:f8:7f:67 brd ff:ff:ff:ff:ff:ff
        inet 192.0.2.161/24 metric 100 brd 192.0.2.255 scope global dynamic enp1s0
           valid_lft 56853sec preferred_lft 56853sec
        inet6 2a05:0000:0000:000:5400:4ff:0000:7f67/64 scope global dynamic mngtmpaddr noprefixroute 
           valid_lft 2591775sec preferred_lft 604575sec
        inet6 2a05:0000:0000:000:5400:4ff:0000:7f67/64 scope link 
           valid_lft forever preferred_lft forever

根据描述信息可知道`enp1s0`是主公网接口，IP地址为`192.0.2.161`。`WireGuard`通过主公网接口将网络请求转换并转发到Internet。

4、生成服务端配置文件

    echo "[Interface]
    PrivateKey = $(cat server_private.key)
    Address = 10.8.0.1/24 
    #如果你的服务器主网卡名称不是 enp1s0 ，那么请修改下面防火墙规则中最后的 enp1s0 为你的主网卡名称。
    PostUp = ufw route allow in on wg0 out on enp1s0
    PostUp = iptables -t nat -I POSTROUTING -o enp1s0 -j MASQUERADE
    PreDown = ufw route delete allow in on wg0 out on enp1s0
    PreDown = iptables -t nat -D POSTROUTING -o enp1s0 -j MASQUERADE
    ListenPort = 51820
    DNS = 8.8.8.8
    MTU = 1420
    "|sed '/^#/d;/^\s*$/d' > wg0.conf

`ListenPort`为端口号，可以设置成自己想使用的端口。

### 客户端配置(如需增加客户端，重复以下步骤即可)

1、生成客户端私钥：

    wg genkey | sudo tee /etc/wireguard/client1_private.key

输出如下：

    KBUxCUqNEJqN3DBO5xu2kiBQFT8Gv46Kkqu6OIKZu3Q=

2、生成客户端公钥：

    cat /etc/wireguard/client1_private.key | wg pubkey | sudo tee /etc/wireguard/client1_public.key

输出如下：

    xZB9I6953ebGqWVLCR7L6yJw7YJi0shJ+Sub9gfUFVU=

3、生成客户端配置文件：

```shell
[Interface]
PrivateKey = +B1l4bteT0URxs47VL7mSUJ6Gjp2yrXsxuzGWQBPSUo=
Address = 10.8.0.3/24
DNS = 114.114.114.114, 8.8.8.8, 8.8.4.4

[Peer]
PublicKey = rxdt0em+q2ST/ZJwrwiozT5TPCzIyfZbFj/1TPsN02c=
PresharedKey = INzSFYALzwr7o4yiOSaAB4xkHSD9MZiv7HCwt204dAQ=
AllowedIPs = 10.9.0.0/24
Endpoint = 43.136.104.74:51821
```


通过上述配置，客户端设备可以与`WireGuard`服务器建立新的VPN隧道，并通过隧道IP地址`10.8.0.2`访问internet。

4、打开`WireGuard`服务器配置，添加新的客户端

将`xZB9I6953ebGqWVLCR7L6yJw7YJi0shJ+Sub9gfUFVU=`替换为客户端公钥：

    [Peer]
    PublicKey = xZB9I6953ebGqWVLCR7L6yJw7YJi0shJ+Sub9gfUFVU=
    AllowedIPs = 10.8.0.2/32

### 管理`WireGuard`服务（服务端、客户端命令相同）

1、启动`WireGuard`：

    systemctl start wg-quick@wg0.service
或者
    #启动
    wg-quick up wg0
**注意：**文件名wg0.conf意味着wg0将是在客户端启动WireGuard连接的名字。可配置多个服务，根据/etc/wireguard/目录下配置文件名称来，wg0.confwei wg0服务，wg1.confwei wg1服务。
2、配置`WireGuard`开机启动：

    systemctl enable wg-quick@wg0.service

3、查看`WireGuard`状态：

    systemctl status wg-quick@wg0.service

正确输出如下：

    ● wg-quick@wg0.service - WireGuard via wg-quick(8) for wg0
         Loaded: loaded (/usr/lib/systemd/system/wg-quick@.service; disabled; preset: enabled)
         Active: active (exited) since Wed 2024-06-12 04:47:53 UTC; 38s ago
           Docs: man:wg-quick(8)
                 man:wg(8)
                 https://www.wireguard.com/
                 https://www.wireguard.com/quickstart/
                 https://git.zx2c4.com/wireguard-tools/about/src/man/wg-quick.8
                 https://git.zx2c4.com/wireguard-tools/about/src/man/wg.8
        Process: 2384 ExecStart=/usr/bin/wg-quick up wg0 (code=exited, status=0/SUCCESS)
       Main PID: 2384 (code=exited, status=0/SUCCESS)
            CPU: 125ms

4、查看`WireGuard`虚拟网卡当前状态：

    wg

或者

    wg show wg0

输出如下：

    interface: wg0
      public key: W+l7Uapd98bsNhN1g3Hs4iTCfKzcV03KNwhDPFgzqR4=
      private key: (hidden)
      listening port: 51820
    
    peer: xZB9I6953ebGqWVLCR7L6yJw7YJi0shJ+Sub9gfUFVU=
      allowed ips: 10.8.0.2/32

5、停止`WireGuard`服务

    wg-quick down wg0

### 测试配置

多台机器互`ping`即可：

    ping -c 4 10.8.0.1

能ping通，说明`WireGuard`安装成功。

输出如下：

    PING 10.8.0.1 (10.8.0.1) 56(84) bytes of data.
    64 bytes from 10.8.0.1: icmp_seq=1 ttl=64 time=0.056 ms
    64 bytes from 10.8.0.1: icmp_seq=2 ttl=64 time=0.076 ms
    64 bytes from 10.8.0.1: icmp_seq=3 ttl=64 time=0.064 ms
    64 bytes from 10.8.0.1: icmp_seq=4 ttl=64 time=0.065 ms
    
    --- 10.8.0.1 ping statistics ---
    4 packets transmitted, 4 received, 0% packet loss, time 3049ms
    rtt min/avg/max/mdev = 0.056/0.065/0.076/0.007 ms

### 防火墙配置

默认情况下，`Uncomplicated Firewall` （`UFW`）在`Ubuntu 24.04`服务器上是激活的。这时需要配置防火墙允许在配置中指定的`51820`端口上进行网络连接。此外，还需要在服务器上开启端口转发功能，以便通过`NAT` （`Network Address Translation`）将来自`WireGuard`接口地址的网络请求转发到internet。

查看防火墙状态：

    ufw status

当`UFW`状态为`inactive`时，执行如下命令允许SSH端口，并开启防火墙。

    ufw allow 22 && sudo ufw enable

允许`WireGuard`接口`UDP`端口`51820`通过防火墙:

    ufw allow 51820/udp

重新加载`UFW`

    ufw reload

再次查看`UFW`状态：

    ufw status

输出如下：

```shell
	Status: active
    
    To                         Action      From
    
    22/tcp                     ALLOW       Anywhere                  
    51820/udp                  ALLOW       Anywhere                  
    22/tcp (v6)                ALLOW       Anywhere (v6)             
    51820/udp (v6)             ALLOW       Anywhere (v6)             
    
    Anywhere on enp1s0         ALLOW FWD   Anywhere on wg0           
    Anywhere (v6) on enp1s0    ALLOW FWD   Anywhere (v6) on wg0
```

配置`iptables`规则：

```shell
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o enp1s0 -j MASQUERADE
```

注意将`enp1s0`改成自己的网卡。

保存规则：

```shell
iptables-save | sudo tee /etc/iptables/rules.v4
```

# 使用 Certbot 获取免费 HTTPS 证书

### 为什么选择 Certbot 和 Let’s [Encrypt](https://so.csdn.net/so/search?q=Encrypt&spm=1001.2101.3001.7020)？

Let’s Encrypt 是一个由非营利组织 ISRG 提供的免费证书颁发机构，Certbot 则是其官方推荐的自动化工具。它们的核心优势包括：

*   **免费**：无需支付证书费用。
*   **自动化**：Certbot 提供自动获取和续期证书的功能。
*   **开源**：社区支持广泛，兼容多种服务器环境。
*   **快速**：几分钟即可完成配置。

无论你是运行一个个人博客还是小型商业网站，Certbot 都能帮你快速实现 HTTPS。

### 前置条件

在开始之前，请确保你已准备好以下内容：

1.  **一个域名**：已解析到你的服务器 IP。
2.  **服务器环境**：支持 Linux（如 Ubuntu、CentOS）或类似系统。
3.  **Web 服务器**：已安装 Nginx 或 Apache。
4.  **管理员权限**：需要 root 或 sudo 权限来执行命令。

本文以 Ubuntu 20.04 和 Nginx 为例，其他环境配置类似，可参考 Certbot 官网。

### 配置流程

下面是使用 Certbot 获取和配置 HTTPS 证书的完整流程。整个过程可以分为五个步骤：

准备服务器和域名

安装 Certbot

获取 HTTPS 证书

配置 Web 服务器

设置自动续期

#### 步骤 1：安装 Certbot

Certbot 的安装非常简单，推荐使用 snap 安装方式，因为它能确保获取最新版本。

在 Ubuntu 系统上，运行以下命令：

    sudo snap install core; sudo snap refresh core
    sudo snap install --classic certbot
    sudo ln -s /snap/bin/certbot /usr/bin/certbot
    

验证安装是否成功：

    certbot --version
    

输出类似 `certbot 2.x.x` 说明安装完成。

#### 步骤 2：获取 HTTPS 证书

Certbot 支持多种验证方式，这里我们使用 `--nginx` 插件（适用于 Nginx 用户），它会自动验证域名并修改 Nginx 配置。如果你是 Apache 用户，可以替换为 `--apache`。

运行以下命令：

    sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
	sudo certbot --nginx --nginx-server-root=/www/server/nginx/conf -d easytribe.bakeding.site
    

*   `-d` 指定需要 HTTPS 的域名，可以多次使用以支持多个子域名。
*   Certbot 会通过 HTTP-01 挑战验证域名所有权，确保你的域名指向当前服务器。

执行过程中，Certbot 会提示你输入邮箱（用于续期通知）和同意服务条款。完成后，证书将存储在 `/etc/letsencrypt/live/yourdomain.com/` 目录下。

#### 步骤 3：配置 Web 服务器

如果你使用 `--nginx` 插件，Certbot 会自动修改 Nginx 配置文件，添加 HTTPS 支持。你可以检查配置文件（通常在 `/etc/nginx/sites-available/`）：

    server {
        listen 80;
        server_name yourdomain.com www.yourdomain.com;
        return 301 https://$host$request_uri;
    }
    
    server {
        listen 443 ssl;
        server_name yourdomain.com www.yourdomain.com;
    
        ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    
        # 其他配置...
    }
    

如果 Certbot 未自动配置，你需要手动添加上述 HTTPS server 块，并重启 Nginx：

    sudo nginx -t
    sudo systemctl reload nginx
    

#### 步骤 4：测试 HTTPS

在浏览器中访问 `https://yourdomain.com`，检查是否加载正常。你也可以使用在线工具（如 SSL Labs 的 SSL Server Test）检查证书状态。

#### 步骤 5：设置自动续期

Let’s Encrypt 证书有效期为 90 天，Certbot 提供自动续期功能。测试自动续期是否正常工作：

    sudo certbot renew --dry-run
    

如果没有报错，说明续期配置正常。Certbot 默认会通过 cron 或 systemd 定时任务自动续期。你可以查看 systemd 定时任务：

    sudo systemctl status snap.certbot.renew.service
    

确保服务是启用状态，通常 Certbot 会每天尝试续期。

### 常见问题与解决方案

1.  **“DNS 解析错误”怎么办？**
    
    确保域名已正确解析到服务器 IP。使用 `dig yourdomain.com` 或 `nslookup` 检查 DNS 状态。
    
2.  **Nginx 配置未自动更新？**
    
    手动检查 `/etc/letsencrypt/live/yourdomain.com/` 下的证书路径，并更新 Nginx 配置文件。
    
3.  **续期失败？**
    
    检查服务器是否允许 80 端口访问，Let’s Encrypt 需要通过 HTTP 验证续期。
    
4.  **多域名支持？**
    
    在获取证书时，添加多个 `-d` 参数，如 `-d yourdomain.com -d www.yourdomain.com -d api.yourdomain.com`。
    

### 小贴士

*   **备份证书**：定期备份 `/etc/letsencrypt/` 目录，避免意外丢失。
*   **强制 HTTPS**：在 Nginx 配置中添加 301 重定向，确保所有 HTTP 流量跳转到 HTTPS。
*   **监控续期**：可以通过邮件通知或脚本监控续期状态。

### 总结

通过 Certbot 和 Let’s Encrypt，任何人都能轻松为网站启用 HTTPS。整个过程简单高效，从安装到配置只需几分钟，且自动续期功能让维护变得无忧。希望这篇教程能帮你快速上手 HTTPS 配置，让你的网站更安全、更专业！

如果有任何问题，欢迎在评论区交流，或者访问 [Certbot 官网](https://certbot.eff.org/) 获取更多帮助。
[使用 Certbot 获取免费 HTTPS 证书：从零开始的 HTTPS 配置指南-](https://blog.csdn.net/problc/article/details/148292129 "使用 Certbot 获取免费 HTTPS 证书：从零开始的 HTTPS 配置指南-")
[使用 Let’s Encrypt 免费申请泛域名 SSL 证书，并实现自动续期](https://www.cnblogs.com/michaelshen/p/18538178 "使用 Let’s Encrypt 免费申请泛域名 SSL 证书，并实现自动续期")