docker-compose.yml container_name and hostname

hostname: just sets what the container believes its own hostname is. In the unusual event you got a shell inside the container, it might show up in the prompt. It has no effect on anything outside, and there’s usually no point in setting it. (It has basically the same effect as hostname(1): that command doesn’t cause anything outside your host to know the name you set.)

container_name: sets the actual name of the container when it runs, rather than letting Docker Compose generate it. If this name is different from the name of the block in services:, both names will be usable as DNS names for inter-container communication. Unless you need to use docker to manage a container that Compose started, you usually don’t need to set this either.

If you omit both of these settings, one container can reach another (provided they’re in the same Docker Compose file and have compatible networks: settings) using the name of the services: block and the port the service inside the container is listening in.

version: '3'
services:
  redis:
    image: redis
  db:
    image: mysql
    ports: [6033:3306]
  app:
    build: .
    ports: [12345:8990]
    env:
      REDIS_HOST: redis
      REDIS_PORT: 6379
      MYSQL_HOST: db
      MYSQL_PORT: 3306

The easiest answer is the following:

container_name: This is the container name that you see from the host machine when listing the running containers with the docker container ls command.

hostname: The hostname of the container. Actually, the name that you define here is going to the /etc/hosts file:

$ exec -it myserver /bin/bash

bash-4.2# cat /etc/hosts
127.0.0.1   localhost
172.18.0.2  myserver

That means you can ping machines by that names within a Docker network.

I highly suggest set these two parameters the same to avoid confusion.

An example docker-compose.yml file:

version: '3'
services:
    database-server:
        image: ...
        container_name: database-server
        hostname: database-server
        ports:
            - "xxxx:yyyy"

    web-server:
        image: ...
        container_name: web-server
        hostname: web-server
        ports:
            - "xxxx:xxxx"
            - "5101:4001" # debug port