Docker v1.12 can not change hostname by env variable $HOSTNAME

With previous docker versions, the command of “hostname” and “echo $HOSTNAME” returned same thing, after I changed it by sending an env variable into the image.

Why I use this is that I want to insert a new host into /etc/hosts by invoking hostname or $HOSTNAME. So my service/app inside this docker can get the ‘real’ IP address or the one I assigned, while not the docker internal one.

In the previous docker versions, I can change the hostname by assign env variable HOSTNAME, this will change the hostname correspondingly. But now, with docker version 1.12. This kind of linux action doesn’t work in that linux behavior.

So if compose like this:
version: ‘2’

services:
  test:
    build: .
    extra_hosts:
        thisservice: "192.168.1.7"
    environment:
      - HOSTNAME=thisservice
    image: dockerv1.12-test

inside the docker container, cat /etc/hosts looks like this:

127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
192.168.1.7	thisservice
172.28.0.2	80260fa6667f

While:

$ hostname
80260fa6667f

$ echo $HOSTNAME
thisservice

This is the wrong behavior as I mentioned above, and things like this did not happen with previous docker version.

In this case, the service in the container will have no idea about the IP I assigned but go for the docker internal IP. This is not what I want. And not correct behavior in my opinion.

So is this a bug or on purpose for swarm mode within docker v1.12?

And how could I change the hostname as I need?