Have you ever faced a situation when you need to check which ports are open in the pod with your application? To do this you need to create a pod with Nmap in the cluster and scan the ports. In this article, I share my definition to quickly do that.

apiVersion: v1
kind: Pod
metadata:
  name: ubuntu-with-nmap
  namespace: default
spec:
  containers:
    - name: ubuntu
      image: 'ubuntu'
      securityContext:
          allowPrivilegeEscalation: false
          runAsUser: 0
          capabilities:
            add:
             - NET_RAW
      command: ["/bin/sh"]
      args:
        - -c
        - >-
          apt update &&
          apt install -y nmap &&
          nmap --script-updatedb &&
          echo "container is ready" &&
          sleep 3d

Let's see what's here in detail

Namespace

namespace: default - namespace where the pod will be created

Capabilities

capabilities:
  add:
    - NET_RAW

You can run your Nmap with the --unprivileged argument, but Nmap scanning will be limited in this case. For example, if you need to run a UDP scan, you need additional capabilities. If you'll try to run Nmap and get the following error:

dnet: Failed to open device eth0
QUITTING!

This means that Nmap requires additional permissions. That's why we need to add additional capabilities to the container.

Command and arguments

command: ["/bin/sh"]
args:
  - -c
  - >-
    apt update &&
    apt install -y nmap &&
    nmap --script-updatedb &&
    echo "container is ready" &&
    sleep 3d

You have to have a single entrypoint, which means that you can't have multiple command instructions. That's why you need to construct one long command.

Also you need some sleep command in the end in order to let the container run. If you won't specify the sleep, the container will be rebooted each time it is loaded.

Applying the definition to the cluster

Applying the definition is very simple, you just need to save the content to a yaml file (in the following example the filename is nmap-definition.yaml) and run the command on you cluster:

$ oc create -f nmap-definition.yaml # for OpenShift
$ kubectl create -f nmap-definition.yaml # for Kubernetes

The pod has been created:

$ oc get pods
NAME                READY   STATUS    RESTARTS   AGE
ubuntu-with-nmap    1/1     Running   0          40s