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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)