How do I get into a Docker container?

2019-01-03 18:44发布

I'm getting started working with Docker. I'm using the WordPress base image and docker-compose.

I'm trying to ssh into one of the containers to inspect the files/directories that were created during the initial build. I tried to run docker-compose run containername ls -la, but that didn't do anything. Even if it did, I'd rather have a console where I can traverse the directory structure, rather than run a single command. What is the right way to do this with Docker?

21条回答
来,给爷笑一个
2楼-- · 2019-01-03 19:36

Another option is to use nsenter.

PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)
nsenter --target $PID --mount --uts --ipc --net --pid
查看更多
三岁会撩人
3楼-- · 2019-01-03 19:37

To bash into a running container, type this:

docker exec -t -i container_name /bin/bash
查看更多
Evening l夕情丶
4楼-- · 2019-01-03 19:41

Let's say, for reasons that are your own, you really do want to use SSH. It takes a few steps, but it can be done. Here are the commands that you would run inside the container to set it up...

apt-get update
apt-get install openssh-server

mkdir /var/run/sshd
chmod 0755 /var/run/sshd
/usr/sbin/sshd

useradd --create-home --shell /bin/bash --groups sudo username ## includes 'sudo'
passwd username ## Enter a password

apt-get install x11-apps ## X11 demo applications (optional)
ifconfig | awk '/inet addr/{print substr($2,6)}' ## Display IP address (optional)

Now you can even run graphical applications (if they are installed in the container) using X11 forwarding to the SSH client:

ssh -X username@IPADDRESS
xeyes ## run an X11 demo app in the client

Here are some related resources:

查看更多
三岁会撩人
5楼-- · 2019-01-03 19:41

SSH into a Docker container using this command:

sudo docker exec -i -t (container ID) bash
查看更多
The star\"
6楼-- · 2019-01-03 19:41

docker exec will definitely be a solution. An easy way to work with the question you asked is by mounting the directory inside Docker to the local system's directory.

So that you can view the changes in local path instantly.

docker run -v /Users/<path>:/<container path> 
查看更多
劫难
7楼-- · 2019-01-03 19:42

GOINSIDE SOLUTION

install goinside command line tool with:

sudo npm install -g goinside

and go inside a docker container with a proper terminal size with:

goinside docker_container_name

old answer

We've put this snippet in ~/.profile:

goinside(){
    docker exec -it $1 bash -c "stty cols $COLUMNS rows $LINES && bash";
}
export -f goinside

Not only does this make everyone able to get inside a running container with:

goinside containername

It also solves a long lived problem about fixed Docker container terminal sizes. Which is very annoying if you face it.

Also if you follow the link you'll have command completion for your docker container names too.

查看更多
登录 后发表回答