How to .bashrc for root in Docker

2020-07-01 03:10发布

I want to give my root user in a (centos:6) Docker container a .bashrc. However, when I run my container, I find that the .bashrc has not been sourced. Can this be done?

My build command:

...
RUN touch .bashrc
RUN echo "iptables -t nat -A OUTPUT -d hostA -p tcp --dport 3306 -j DNAT --to hostB" >> .bashrc
...

My run command:

docker run -it --cap-add=NET_ADMIN myImage /bin/bash

2条回答
贪生不怕死
2楼-- · 2020-07-01 03:23

The bash manpage states that .bashrc is read when the shell is interactive. Thus, if you want a bash that reads .bashrc, you need to launch bash with -i.

See that:

root@host:~# echo 'echo this is .bashrc' > /tmp/bashrc
root@host:~# docker run -ti -v /tmp/bashrc:/root/.bashrc debian bash -i 
this is .bashrc
root@01da3a7e9594:/#

But, executing bash -i like this in the container, overrides the entrypoint or cmd, so you might be better with wrapping the iptables command and the entrypoint you are originally using in a shell script that becomes your entrypoint / cmd.

查看更多
对你真心纯属浪费
3楼-- · 2020-07-01 03:30

Turns out I was adding the file incorrectly. It should be /root/.bashrc rather than just .bashrc. With the file added in the correct place, no run command or CMD is required.

Build

...
ADD iptables /iptables
RUN touch /root/.bashrc \
 && cat iptables >> /root/.bashrc
...

Run

docker run -it --cap-add=NET_ADMIN myImage /bin/bash
查看更多
登录 后发表回答