bash - 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 ssh
ing 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?
解决方案
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
推荐阅读
- java - Swagger 注释别名不会生成正确的 OpenAPI
- java - 使用 okHttp 4.* 将 json 数据发布到 rest api 时,响应代码为 400 的错误请求
- haskell - 自定义 QuickCheck 失败消息
- file - 如何在 Julia 中获取当前工作目录的父目录
- php - Facebook 目标搜索:搜索一个城市的所有邮政编码
- python - Azure Python 部署 - Spacy nomodule 发现异常
- powershell - 具有多个 smtps 时提取主 SMTP 的 Powershell 问题
- java - 循环外临时数组的空间复杂度
- r - 为什么在手动计算和使用 stat_summary 时这两个平均值不匹配?
- f# - 有没有更好的方法在 F#/OCaml 中编写交换函数?