乐闻世界logo
搜索文章和话题

How do I set hostname in docker- compose ?

1个答案

1

Setting the hostname for services in the docker-compose.yml file is straightforward. You can use the hostname field to specify the hostname for each service. After this configuration, when the container starts, it will use the specified hostname instead of the default randomly assigned hostname.

Here is a simple example demonstrating how to set hostnames in a docker-compose file:

yaml
version: '3.8' services: webapp: image: my-web-app:latest hostname: mycustomhostname ports: - "5000:5000" database: image: postgres:latest hostname: mycustomdbhost environment: POSTGRES_DB: mydb POSTGRES_USER: user POSTGRES_PASSWORD: password

In this example:

  • webapp service uses the my-web-app:latest image and sets the hostname to mycustomhostname.
  • database service uses the postgres:latest image and sets the hostname to mycustomdbhost.

After this configuration, the containers within the services will use the specified hostname instead of the default one assigned by Docker. This is particularly useful in a multi-container environment, as it allows for more convenient network communication and service discovery via hostnames.

2024年7月21日 20:14 回复

你的答案