Docker Community Forums

Share and learn in the Docker community.

Question regarding setting a container's hostname


(Robvelor) #1

Is it possible to set a container’s hostname to the hostmachine’s hostname or perhaps container name (the one docker assigns not a custom one)?

I want to set it though compose file (hostname: ) or docker run but using the container name (the dynamic one docker assigns PROJECT_SERVICENAME_X) or set it to the host machine hostname… again dynamically not hardcoded. Think in a swarm network for example. Is there a Docker specific environment variable or something similar?


(Joshnw) #2

Using environment variables in a version 2 compose file

You can define an environment variable that can then be referenced within a compose file. Referenced variables are called as ${VARIABLE_NAME}

Example:

Initialize variables

export CUSTOM_CONTAINER_NAME="string value"
export CUSTOME_CONTAINER_HOSTNAME="string value"

reference the enviroment variables within the compose yaml file and use the hostname and container_name options.

version 2

services: 
  <SERVICE_NAME>:
    image: custom-base
    container_name: ${CUSTOM_CONTAINER_NAME}
    hostname: ${CUSTOME_CONTAINER_HOSTNAME}
    mem_limit: 4G
    restart: always

reference


(Robvelor) #3

I know I can do that but I don’t want to hardcode anything. I want to set it either to the host machine’s hostname or docker’s automatic naming. For example docker does this:{PROJECT_NAME}_{SERVICE_NAME}_{CONSECUTIVE_NUMBER}