Kubernetes: Tunneling through a Pod with socat

kubernetes Pod tunneling socat port-forward

2 min read | by Jordi Prats

When you need to connect to some service as if you were in the same network as the Kubernetes cluster, you can use a Pod with socat to create a tunnel to the service.

First you'll have to create the Pod, instructing socat to listen on a port and forward the traffic to the service you want to connect to. For example, to forward traffic from port 3306 to a MySQL service, you can create a Pod like this:

apiVersion: v1
kind: Pod
metadata:
  name: tcpproxy
spec:
  containers:
  - args:
    - TCP-LISTEN:3306,fork
    - TCP:example-rds.cluster-abcdefghijkl.us-west-2.rds.amazonaws.com:3306
    image: alpine/socat:latest
    name: tcpproxy
    ports:
    - containerPort: 3306

Once the Pod is running, you'll have to start a port-forwarding to the Pod:

kubectl port-forward pod/tcpproxy 3306:3306

This is going to create a tunnel from your local machine to the Pod. Now you can connect to the MySQL service as if it were running on your local machine:

$ mysql --local-infile=1 -h 127.0.0.1 -uadmin -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 263848
Server version: 8.0.23 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> load data local infile '/Users/jordiprats/tmp/demodata.csv' into table demo.demo(id);
Query OK, 3 rows affected (0.13 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select * from demo.demo;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
+------+
3 rows in set (0.07 sec)

mysql> ^DBye

Posted on 28/08/2024