The exec way
First run a container
docker run -it test
Next, you can use the exec
Get the docker container id
docker ps
Run exec on the container id
docker exec -it 0ec2333ec307 /bin/bash/
In this way, you can execute multiple commands in the docker container.
Alternatively, you can also directly execute the commands you want instead of
/bin/bash
I have encountered a use case where I have to run two Java programs in the same container. So, I started an interactive shell, which could also be done by directly executing the java command instead of /bin/bash
The sshd way,
You can have the
sshd
service up and running so that you can directly start an ssh session to your container. This is a bit more complex method compared to the aforementioned, but you can find it useful if you want access the container from outside of your host machine where there is no docker client.For CentOS, RHEL
yum install openssh-server
systemctl enable sshd
systemctl start sshd
If you want to have root access, you need to add the following line to sshd-config
vi /etc/ssh/sshd_config
PermitRootLogin yes
If the line is already there uncomment it (just remove the # before the line)
Note: If you cannot access ssh from outside of the host, it may be because of the iptables rules. Make sure that the rules allow incoming connections to your ssh port.
You may also need to map your container’s ssh port to your host port using the
The above command then would be:
-p
option.The above command then would be:
docker run -it p 22 test
This will map the port 22 of the test container to a randomly chosen port on the host. You can view the port that is assigned using the
docker ps
command.
Now, allow incoming connections to this randomly chosen port by editing the iptables rules of the host machine to allow incoming ssh connections to this port.
Tip: Though in this example, I have used
-p 22
, it is not recommended you do the same in production. You need to manually assign a port of your choice using -p <my_port>:22
iptables -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT
Instead of
eth0
you can use your interface name or you can omit -i eth0
to apply the rule for all interfaces.- -A is for appending a rule to a chain (here INPUT).
- -i is for interface
- -p is the type of packet (tcp, here)
- --dport means destination port (22 for ssh)
- -j is jump which tells what to do when a tcp packet from port 22 comes
Note: Make sure that you don’t append this rule after the drop-all packets rule. The above is just an example, but the command might change for you depending on your iptables rules. So, change them accordingly.
No comments:
Post a Comment