gpt4 book ai didi

docker - Docker-compose多个端口公开

转载 作者:行者123 更新时间:2023-12-02 19:03:22 25 4
gpt4 key购买 nike

我的问题是关于从ENV变量示例在一行中公开多个端口,这些端口不是顺序的,来自主机的相同端口在容器上将是相同的。

PORTS=80
PORTS=80,443
PORTS=80 443
并以 docker-compose公开它们。
根据 docs,您可以做。
ports:
- "3000"
- "3000-3005"
- "8000:8000"
- "9090-9091:8080-8081"
- "49100:22"
- "127.0.0.1:8001:8001"
- "127.0.0.1:5000-5010:5000-5010"
- "6060:6060/udp"
但是我想用另一种可变的方式来做
ports:
- ${PORTS}:${PORTS}
#Sometimes this will be
ports:
- 80:80

#Other times this will be
ports:
- 80,443:80,443 # Is this possible?
ports:
- 80-443:80-443 # Don't want this because will export all the ports between
ports:
- 80 443:80 443 # I think this is wrong syntax
有任何线索或其他想法吗?

最佳答案

IIUC,您不能动态指定ports映射。

Docker Compose YAML文件主要是静态配置。

解决您的问题的一种方法是生成(ports部分)YAML文件。

您可以并且使用sed之类的工具来用一些生成的输出替换Compose文件中的变量。

假设您有docker-compose.yaml:

  service:
...
{{PORTS}}

然后

# List of ports to create
PORTS="80 443 8888"

# Generates "80:80""443:443""8888:8888" NB no commas between items
PORTS=$(for PORT in ${PORTS}; do printf '"%s:%s"' ${PORT} ${PORT}; done)

# Separate items with commas
PORTS=$(echo ${PORTS} | sed 's|""|","|g')

# Finalize the syntax for ports
PORTS="ports: [${PORTS}]"

# Replace {{TEMPLATE}} with the result
sed "s|{{PORTS}}|${PORTS}|g" docker-compose.yaml > docker-compose.new.yaml

会产生 docker-compose.new.yaml:
  service:
...
ports: ["80:80","443:443","8888:8888"]

它不是很优雅,但是足够了。

注意:为了方便起见,我将端口生成为JSON(以避免换行符出现问题)。 YAML是JSON的超集,因此您可以对Docker Compose文件使用JSON而不是YAML。

Google(我的老板)有一个非常好的工具,可以使用基于JSON的模板语言 Jsonnet生成JSON(!)。由于YAML是JSON的超集,因此您可以在Docker Compose文件中使用JSON代替YAML。

Jsonnet:
local ports = ["80", "443", "8888"]; 
{"service":{
"ports": [
port + ":" + port
for port in ports
]
}}

产生:
{
"service": {
"ports": [
"80:80",
"443:443",
"8888:8888"
]
}
}

关于docker - Docker-compose多个端口公开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56690523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com