2022年11月4日 星期五

[lxc, proxy] How to setup a proxy device to your container for your service

How to setup a proxy device to your container for your service

井民全, Jing, mqjing@gmail.com

This document shows you how to create a web service (here I use ngix) behind in a LXC container and setup a proxy device to redirect all TCP:8080 traffics to the ngix service on the container TCP localhost:80.


The following command means: The proxy device listen on any network interfaces on host to TCP:8080, and map to the container on TCP:80

lxc config device add ubuntu-container myport80 proxy listen=tcp:0.0.0.0:8080 connect=tcp:127.0.0.1:80 


Quick

# setup lxc container

sudo snap install lxd --channel=5.0/stable

sudo lxd init

sudo lxc launch images:ubuntu/20.04 ubuntu-container  # launch a container

lxc exec ubuntu-container -- passwd ubuntu  # change the user ubuntu passwd


# verify

sudo lxd list


# Install a test service

lxc exec ubuntu-container -- sudo apt install -y nginx


# add proxy device to the container

lxc config device add ubuntu-container myport80 proxy listen=tcp:0.0.0.0:8080 connect=tcp:127.0.0.1:80 


# verify

[on host]

curl 192.168.1.100:8080

[on the other host]

gio open http://192.168.1.100:8080



Procedure

Step 1: Setup a LXC Container

sudo snap install lxd --channel=5.0/stable

sudo lxd init

sudo lxc launch images:ubuntu/20.04 ubuntu-container  # launch a container

lxc exec ubuntu-container -- passwd ubuntu  # change the user ubuntu passwd


# verify

sudo lxd list


Step 2: Install ngix on the container

lxc exec ubuntu-container -- sudo apt install -y nginx


Verify

curl 10.199.76.115


E.g.


Step 3: Add a proxy device

Create a proxy device named as  myport80 to the container, ubuntu-container. The proxy listen on the host to all network interfaces on TCP:8080 and then redirect the traffic to the container to the port 80 on 127.0.0.1 (localhost), which your service listen on.



lxc config device add ubuntu-container myport80 proxy listen=tcp:0.0.0.0:8080 connect=tcp:127.0.0.1:80 


E.g.


Verification

Test 1: Host test: 

Try to send traffic to the host ip:8080 port, see the service on container responses.

[on host]

curl 192.168.1.100:8080



Test 2: Another machine test

Try to send traffic from another machine to the host ip:8080, see the service on container responses.



[on the other host]

gio open http://192.168.1.100:8080




Reference

  1. https://blog.simos.info/how-to-use-the-lxd-proxy-device-to-map-ports-between-the-host-and-the-containers/