我正在尝试为我的APP分配一个静态IP。我想我已经分配了IP,但我无法从curl或浏览器外部访问IP。
docker-compose.yaml
version: '3.8'
services:
client:
container_name: client
build: ./frontend
ports:
- 3000:3000
working_dir: /app
volumes:
- ./frontend:/app/
- /app/node_modules
networks:
app_net:
ipv4_address: 172.16.238.10
hostname: client
command: npm run dev
networks:
app_net:
driver: bridge
ipam:
driver: default
config:
- subnet: "172.16.238.0/24"
运行时的终端消息:
client | > frontend@0.0.0 dev
client | > vite
client |
client |
client | VITE v3.2.2 ready in 710 ms
client |
client | ➜ Local: http://localhost:3000/
client | ➜ Network: http://172.16.238.10:3000/
我可以在浏览器上访问http://localhost:3000/
。但每当我尝试到达http://172.16.238.10:3000/
时,我都会超时。浏览器上有这样的东西:
This site can’t be reached
172.16.238.10 took too long to respond.
ERR_CONNECTION_TIMED_OUT
我可以卷曲到我在docker容器内分配的IP,但我不能从外部进行。是否可以将IP暴露在外部?
您可能希望考虑使用macvlan网络而不是桥接网络。
如果您设法为主机分配另一个IP地址(172.16.238.10(,则容器可以继续具有动态IP地址。您只能将端口3000映射到IP地址172.16.238.10。
然后您可以按如下方式连接到172.16.238.10:3000:
version: '3.8'
services:
client:
container_name: client
build: ./frontend
ports:
- 172.16.238.10:3000:3000
working_dir: /app
volumes:
- ./frontend:/app/
- /app/node_modules
networks:
- app_net
hostname: client
command: npm run dev
networks:
app_net:
driver: bridge
一般来说,您根本无法访问容器专用IP地址。这恰好在本机Linux上是可能的,不使用Docker Desktop或其他基于VM的设置,并且只有当你和容器在同一台机器上时,但考虑到所有这些限制,通常最好不要尝试。
从外部访问容器的标准方法是为其声明ports:
,并使用主机的DNS名称或IP地址以及发布的端口号。不要在Compose文件中声明任何与IP相关的设置。
假设您的Dockerfile构造正确,您应该能够将Compose文件简化为
version: '3.8'
services:
client:
build: ./frontend
ports:
- 3000:3000
使用主机的DNS名称调用http://host.example.com:3000/
,如果在同一主机上,则调用http://localhost:3000
,将转发到容器中的端口3000。不需要任何其他"合成"选项。