Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to .bashrc for root in Docker

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
like image 566
Matthew Herbst Avatar asked May 17 '16 19:05

Matthew Herbst


People also ask

How do I get root access in docker?

Docker containers are designed to be accessed as root users to execute commands that non-root users can't execute. We can run a command in a running container using the docker exec. We'll use the -i and -t option of the docker exec command to get the interactive shell with TTY terminal access.

What is the root path of docker container?

The docker root dir is the root path where all data docker is stored.

Does docker run containers as root?

One of the best practices while running Docker Container is to run processes with a non-root user. This is because if a user manages to break out of the application running as root in the container, he may gain root user access on host.


2 Answers

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
like image 172
Matthew Herbst Avatar answered Oct 16 '22 15:10

Matthew Herbst


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.

like image 9
smaftoul Avatar answered Oct 16 '22 15:10

smaftoul