Docker容器无法连接Ubuntu主机端口问题求助
Docker容器无法连接Ubuntu主机本地MongoDB的解决
环境信息
- 系统:Ubuntu 18.04.6 LTS
- Docker版本:20.10.22,构建3a2c30b
- 容器访问情况:curl
172.17.0.1或host.docker.internal可访问主机Nginx页面,但访问MongoDB端口时无输出 - Windows环境对比:相同配置可正常连接,
host.docker.internal对应IP为192.168.65.2
相关配置文件
Dockerfile
# build step # Base image FROM node:18 # Create app directory WORKDIR /usr/src/app # A wildcard is used to ensure both package.json AND package-lock.json are copied COPY package*.json ./ # Install app dependencies RUN npm install # Bundle app source COPY . . # Creates a "dist" folder with the production build RUN npm run build # Start the server using the production build CMD [ "node", "dist/main.js" ]
docker-compose.yml
version: '3.8' services: api: build: . container_name: api-container volumes: - .:/app - /app/node_modules ports: - 127.0.0.1:${APP_PORT}:${APP_PORT} env_file: - .env
排查与解决步骤
1. 修改MongoDB绑定地址
默认MongoDB仅绑定127.0.0.1,容器无法通过该地址访问。编辑MongoDB配置文件(通常为/etc/mongod.conf):
- 找到
net.bindIp项,将值改为0.0.0.0(允许所有IP访问),或添加Docker网桥网段172.17.0.0/16 - 重启MongoDB服务:
sudo systemctl restart mongod
2. 配置Ubuntu防火墙规则
Ubuntu默认启用ufw,需允许Docker网段访问MongoDB默认端口27017:
sudo ufw allow from 172.17.0.0/16 to any port 27017 sudo ufw reload
3. 启用Linux下host.docker.internal映射
Docker Linux版本默认未配置host.docker.internal,需在docker-compose.yml中添加映射:
修改api服务配置,增加extra_hosts项:
services: api: # 保留原有配置 extra_hosts: - "host.docker.internal:host-gateway"
此配置会将host.docker.internal指向主机网关地址(即172.17.0.1)
4. 验证容器内连接
进入容器测试MongoDB连接:
docker exec -it api-container bash # 若容器内无Mongo客户端,执行以下安装 apt update && apt install -y mongodb-clients # 测试连接 mongo --host host.docker.internal --port 27017
5. 检查应用连接配置
确认.env文件中应用的MongoDB连接地址为host.docker.internal:27017或172.17.0.1:27017,确保端口与MongoDB实际监听端口一致
内容的提问来源于stack exchange,提问作者Eugene
相关产品推荐
相关产品推荐

