Featured image of post Use VPN inside a Kubernetes pod

Use VPN inside a Kubernetes pod

VPN is handy when you need to access resources that are not available in your LAN or WAN. It is also possible to utilize it inside Kubernetes workloads.

Prerequisites

  1. A Kubernetes cluster
  2. An account with a VPN provider

VPN provider

For me, Private Internet Access is working like a charm.

For other options, check out gluetun’s documentation.

Manifest

Here is a simple example to deploy a pod that uses VPN. The vpn-client container can be any image that you want to use the VPN with.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
apiVersion: apps/v1
kind: Deployment
metadata:
  name: vpn-client
  namespace: example
  labels:
    app: vpn-client
spec:
  replicas: 1
  selector:
    matchLabels:
      app: vpn-client
  template:
    metadata:
      labels:
        app: vpn-client
    spec:
      initContainers:
      - name: gluetun
        restartPolicy: Always
        image: ghcr.io/qdm12/gluetun
        imagePullPolicy: Always
        securityContext:
          capabilities:
            add:
            - 'NET_ADMIN'
        env:
        - name: TZ
          value: 'America/Denver'
        - name: VPN_SERVICE_PROVIDER
          value: private internet access
        - name: OPENVPN_USER
          value: "<YOUR_USERNAME>"
        - name: OPENVPN_PASSWORD
          value: "<YOUR_PASSWORD>"
      - name: wait-for-vpn
        image: curlimages/curl:latest
        command:
          - /bin/sh
          - -c
          - |
            echo "Waiting for VPN activate..."
            while true; do
              CURRENT_IP=$(curl -s icanhazip.com)
              
              if [ -z "$CURRENT_IP" ]; then
                echo "VPN not ready, retrying..."
                sleep 5
              else
                echo "VPN is up! IP: $CURRENT_IP"
                exit 0
              fi
            done            
      dnsPolicy: "None"
      dnsConfig:
        nameservers:
          - 10.11.110.1
      containers:
      - name: vpn-client
        image: registry.k8s.io/e2e-test-images/agnhost:2.39
        command: ["tail", "-f", "/dev/null"]

Confirmation

Look for logs similar to the following in the pod:

1
2
gluetun INFO [ip getter] Public IP address is <VPN_IP>
wait-for-vpn VPN is up! IP: <VPN_IP>

You can also confirm yourself by running something like curl icanhazip.com inside the pod.

Built with Hugo
Theme Stack designed by Jimmy