我想使用主机名从Docker主机连接到Docker容器。
我已经知道如何使用docker run -p <host-port>:<container-port> ...
映射容器的端口,然后通过localhost
访问它们来连接到容器。
此外,我可以使用docker inspect <container>
给出的IP地址连接到容器。但是这些IP地址不是一成不变的。
如何赋予容器主机名,以便我可以通过暴露的端口连接到它们,而不必考虑非静态IP?
答案 0 :(得分:1)
使用docker-compose
并在其中进行服务。每个容器都是服务的一部分,并且一个容器可以使用该容器所属的服务名称与其他容器进行通话。
例如:
$ cat docker-compose.yml
version: '3.1'
services:
server:
image: redis
command: [ "redis-server" ]
client:
image: redis
command: [ "redis-cli", "-h", "server", "ping" ]
links:
- server
$
$
$ docker-compose up
Starting server_1 ... done
Starting client_1 ... done
Attaching to server_1, client_1
client_1 | PONG
server_1 | 1:C 10 Dec 2019 12:59:20.161 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
server_1 | 1:C 10 Dec 2019 12:59:20.161 # Redis version=5.0.6, bits=64, commit=00000000, modified=0, pid=1, just started
server_1 | 1:C 10 Dec 2019 12:59:20.161 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
server_1 | 1:M 10 Dec 2019 12:59:20.162 * Running mode=standalone, port=6379.
server_1 | 1:M 10 Dec 2019 12:59:20.162 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
server_1 | 1:M 10 Dec 2019 12:59:20.162 # Server initialized
server_1 | 1:M 10 Dec 2019 12:59:20.162 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
server_1 | 1:M 10 Dec 2019 12:59:20.162 * Ready to accept connections
client_1 exited with code 0
在这里,我创建了两个服务,server
和client
。 server
启动Redis服务器,client
尝试连接到服务器。另外,请注意,我这里没有公开端口,因此client
容器正在使用server
(服务名)与server
容器进行通信
client:
image: redis
command: [ "redis-cli", "-h", "server", "ping" ]