在使用 Docker 构建可视化网络监控系统时,一个常见的需求是通过 Web 服务(如 Apache httpd)对运行在 host
网络模式下的容器(如 vnstat
)提供反向代理访问,并确保访问安全性。本文将详细总结一次成功的配置实践,重点解决以下几个核心问题:
一、背景与目标
-
-
vnstat 容器 使用
host
网络模式,便于直接访问宿主机所有网卡信息。 -
httpd 容器 使用 bridge 网络模式,通过反向代理暴露 vnstat 页面。
-
需要 防止外部直接访问 vnstat 端口。
- 配置 基本认证(用户名密码),防止未授权访问 vnstat 面板。
-
二、问题分析与挑战
-
host
网络模式下的容器没有独立 IP,无法通过容器名访问。- 直接通过
127.0.0.1:8685
等本地地址代理,在容器中访问会失败(因为指的是容器自身)。 httpd
默认无法解析host.docker.internal
,需要手动添加extra_hosts
。- 若暴露 vnstat 容器端口(如 8685:8685),则任何外部访问者都可以绕过 Apache 验证直接访问。
三、解决方案概述
1. 使用 host.docker.internal
访问宿主机服务
由于 vnstat
运行在宿主机网络中,可以通过 Apache 使用:
ProxyPass /vnstat http://host.docker.internal:8685/ ProxyPassReverse /vnstat http://host.docker.internal:8685/
注意:Linux Docker 默认不支持 host.docker.internal
,需要手动加入 /etc/hosts
。
2. 在 httpd 容器添加 extra_hosts
在 docker-compose.yml
中为 httpd
容器添加如下配置:
extra_hosts: - "host.docker.internal:host-gateway"
这会将 host.docker.internal
映射为宿主机网关地址,便于容器内访问。
3. 避免暴露 vnstat 容器端口
不要在 vnstat
服务配置中添加:
ports: - "8685:8685"
这可以防止外部用户绕过 Apache 直接访问 http://host:8685
。
4. 配置 Apache 基本认证
在 httpd 配置中添加:
<Proxy "http://host.docker.internal:8685/"> AuthType Basic AuthName "Restricted Access" AuthUserFile /usr/local/apache2/conf/.htpasswd Require valid-user </Proxy>
并在构建镜像或运行时加入 .htpasswd
文件,可使用以下命令生成:
htpasswd -c .htpasswd admin
然后将该文件挂载或复制到容器路径 /usr/local/apache2/conf/.htpasswd
。
四、docker-compose 示例配置
services: vnstat: image: vergoh/vnstat network_mode: host restart: unless-stopped environment: HTTP_BIND: host.docker.internal # 防止绑定 0.0.0.0 # 不暴露端口,避免直接访问 httpd: image: httpd:alpine container_name: httpd restart: always ports: - "80:80" volumes: - ./httpd.conf:/usr/local/apache2/conf/httpd.conf - ./htpasswd:/usr/local/apache2/conf/.htpasswd extra_hosts: - "host.docker.internal:host-gateway"
五、验证效果
-
通过
http://your-server-ip/vnstat
可以访问 vnstat 页面。 -
未登录用户无法访问,需输入用户名和密码。
-
外部用户即使知道
8685
端口也无法访问(未暴露)。 -
Apache 使用
host.docker.internal
成功代理宿主服务。
六、总结
本方案实现了:
将 host
网络模式容器的服务安全地通过反向代理暴露;
避免暴露端口带来的安全风险;
加上基本认证进行访问控制;
不影响 vnstat 的完整网络数据收集能力(因使用 host
网络)。