Set up SSH Access into LXCs

By default, it’s not possible to SSH into LXCs from outside, but we can accomplish that by setting up a SSH server in LXC and some port forwarding magic.

Setup SSH Server in LXC

We assume that the internal IP address of your LXC is 10.0.3.2 (See Assign Static Internal IP Addresses to LXC.).

  1. Log in to the LXC from the host server using the lxc-attach command.
  2. Set a password for the root user by issuing the passwd root command from within the LXC.
  3. Install openssh-server.
  4. Open /etc/ssh/sshd_config file, and set PermitRootLogin to yes.
  5. Restart the SSH service by issuing service ssh restart command.
  6. exit into the host server.
  7. Test the SSH connection by issuing ssh root@10.0.3.2.

If above steps worked, you’ve successfully set up SSH server in your LXC.

Allow SSH Access to LXC from Outside

We are going to dedicate a port in the host system to be used as a gateway to the LXC. Imagine you want to port 2002 of your host to be that gateway. We will forward the 2002 port of the host server to the 22 (Default SSH port.) of LXC.

You can do it by issuing the following command:

PREROUTING -i eth0 -p tcp -m tcp --dport 2002 -j DNAT --to-destination 10.0.3.2:22

Note that this won’t persist in the system after you restart the host server. To persist the setting, we need to install a software called iptables-persistent.

Once that is installed, issue the following command to save the port forwarding rules.

netfilter-persistent save

Your IPv4 rules will be saved in /etc/iptables/rules.v4 and IPv6 rules will be saved in /etc/iptables/rules.v6.

If you make any manual modifications to those file, you can reload those by issuing netfilter-persistent reload command.

Leave a Reply