问题
I've seen a couple posts about this but they do not answer the question of "How does one pass the a host's hostname at build time to a container?"
The reason I need to pass the hostname at build time (in the docker file) instead of at creation time is because I am using docker swarm and if I pass the hostname when I create the service like so I will only get one hostname for every container:
$ docker service create -p <port>:<port> --hostname $HOSTNAME --replicas 4 <image>
By passing the hostname at run time every single container no matter what host that container is actually running on will look as if it is running on The manager node.
How can I pass the hostname value during the docker build process in my docker file?
The reason I need to be able to view the hostname in a container is because every time a container is accessed I want to access a mongo database and increment a view count for the container and for the node in order to display the load balancing feature of a swarm.
What do I need to add to my docker file?
Dockerfile:
FROM resin/raspberry-pi-alpine-node
MAINTAINER brennansaul jamessaul7629@gmail.com
RUN apk --update add nginx php5-fpm && \
mkdir -p /run/nginx
ADD www /www
ADD nginx.conf /etc/nginx/
ADD php-fpm.conf /etc/php5/php-fpm.conf
ADD run.sh /run.sh
ENV LISTEN_PORT=80
EXPOSE 80
CMD /run.sh
Index.php
<html>
<h1><?php echo "Hello ".($_ENV["NAME"]?$_ENV["NAME"]:"world")."!"; ?></h1>
<?php if($_ENV["HOSTNAME"]) {?><h3>My hostname is <?php echo $_ENV["HOSTNAME"]; ?></h3><?php } ?>
<?php if($_ENV["HOST_NAME"]) {?><h3>My hostname is <?php echo $_ENV["HOST_NAME"]; ?></h3><?php } ?>
</html>
Where HOST_NAME would be the variable I assigned the hostname to and HOSTNAME is the container id.
回答1:
It doesn't make sense to use the hostname during build because the basic idea is to build in a central server, then push, then pull from every instance that need to run the image as a container.
So I recomend --mount the hostname file instead:
docker service create \
-p <port>:<port> \
--replicas 4
--mount type=bind,source=/etc/hostname,destination=/tmp/host-hostname,readonly=true \
<image>
Use this PHP:
<h3>My hostname is <?php echo file_get_contents("/tmp/host-hostname"); ?></h3>
回答2:
You don't have to pass the server host name via Docker in this case, you can use $_SERVER['HTTP_HOST'] or gethostname() or other common techniques to get the container id.
来源:https://stackoverflow.com/questions/45443510/passing-the-hostname-to-a-docker-container-at-build