简体   繁体   中英

How to set hosts in docker for mac

When I use docker before, I can use docker-machine ssh default to set hosts in docker's machine /etc/hosts , but in docker for mac I can't access it's VM because of it don't have it. So, the problem is how to set hosts in docker for mac ? My secondary domain wants to point the other ip.

I found a solution, use this command

screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty

Now, edit the /etc/hosts in the Docker VM.
To exit screen , use Ctrl + a + d .

Here's how I do it with a bash script so the changes persist between Docker for Mac restarts.

cd ~/Library/Containers/com.docker.docker/Data/database
git reset --hard

DFM_HOSTS_FILE="com.docker.driver.amd64-linux/etc/hosts"
if [ ! -f ${DFM_HOSTS_FILE} ]; then
  echo "appending host to DFM /etc/hosts"
  echo -e "xxx.xxx.xxx.xxx\tmy.special.host" > ${DFM_HOSTS_FILE}
  git add ${DFM_HOSTS_FILE}
  git commit -m "add host to /etc/hosts for dns lookup"
fi

You can automate it via this script, run this scrip on start up time or login time will save you..

#!/bin/sh 
# host entry -> '10.4.1.4   dockerreigstry.senz.local'
# 1. run debian image
# 2. check host entry exists in /etc/hosts file
# 3. if not exists add it to /etc/hosts file
docker run --name debian -it --privileged --pid=host debian nsenter \
    -t 1 -m -u -n -i sh \
    -c "if ! grep -q dockerregistry.senz.local /etc/hosts; then echo -e '10.4.1.4\tdockerregistry.pagero.local' >> /etc/hosts; fi"

# sleep 2 seconds
# remove stopped debian container
sleep 2
docker rm -f debian

I have created a blog post with more information about this topic.

https://medium.com/@itseranga/set-hosts-in-docker-for-mac-2029276fd448

You must have to create an docker-compose.yml file. This file will be on the same route of your Dockerfile For example, I use this docker-compose.yml file:

version: '2'
services:
  app:
    hostname: app
    build: .
    volumes:
      - ./:/var/www/html
    working_dir: /var/www/html
    depends_on:
      - db
      - cache
    ports:
      - 80:80
  cache:
    image: memcached:1.4.27
    ports:
      - 11211:11211
  rabbitmq:
    image: rabbitmq:latest
    ports:
      - 5672:5672
  db:
    image: postgres:9.5.3
    ports:
      - 5432:5432
    environment:
      - TZ=America/Mazatlan
      - POSTGRES_PASSWORD=root
      - POSTGRES_DB=restaurantcore
      - POSTGRES_USER=rooms
      - POSTGRES_PASSWORD=rooms

The ports are binding with the ports of your host docker machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM