首页 > 解决方案 > How to add an entry to the hosts file inside a Docker container?

问题描述

I have a Kafka instance running on my local machine (macOS Mojave) and I'm trying to have a Docker container see that.

There are two files in the Java program that will be built as the Docker container:

docker-entrypoint.sh:

#!/bin/bash
HOST_DOMAIN="kafka"
HOST_IP=$(awk '/32 host/ { print f } {f=$2}' <<< "$(</proc/net/fib_trie)" | head -n 1)

Dockerfile:

# ...
COPY docker-entrypoint.sh ./
RUN chmod 755 docker-entrypoint.sh
RUN apt-get install -y sudo
CMD ["./docker-entrypoint.sh"]

Now I want to write the following line:

$HOST_IP\t$HOST_DOMAIN

to /etc/hosts so the Docker container can work with Kafka. How can I do that, considering elevated access is needed to write to that file? I have tried these:

1- Changing CMD ["./docker-entrypoint.sh"] to CMD ["sudo", "./docker-entrypoint.sh"]

2- Using sudo tee

3- Using su root;tee ...

4- Running echo "%<user> ALL=(ALL) ALL" | tee -a /etc/sudoers > /dev/null, so I can then tee ... without sudo.

1, 2, and 3 lead to the following error:

sudo: no tty present and no askpass program specified

I don't understand this error. A search for it had solutions for when one is sshing to run a command, but here there is no ssh.

To do 4, I already need to be sudo, correct?

So, how can I achieve what I'm looking to do?

标签: bashmacosdockerapache-kafka

解决方案


Dockerfile commands typically run as root unless you've changed the user account, so you should not need sudo.


You don't need to edit any hosts file

You can use host.docker.internal to reach the host from the container

https://docs.docker.com/docker-for-mac/networking/

Otherwise, just run Kafka in a container if you want to setup things locally


推荐阅读