Intro
Kubernetes init containers run before application containers in a pod and are commonly used for setup tasks such as waiting for a database, fetching configuration, or performing migrations. These containers execute in the same network namespace as the pod, meaning they share the pod IP address and port space. However, they have their own filesystem and process namespace, and they must complete successfully before the main containers start. Networking problems in init containers are a frequent source of pod startup failures, yet they are often overlooked because the init container may exit before you can inspect it.
This guide provides a practical, step-by-step approach to troubleshooting networking issues in Kubernetes init containers. You will learn how to identify DNS resolution failures, port conflicts, routing problems, firewall restrictions, and connectivity issues using concrete commands and configuration snippets. Each major step includes examples with expected outputs so you can compare against your environment.
By the end, you will have a repeatable process to diagnose and fix init container networking problems, reduce pod startup failures, and improve the reliability of your Kubernetes workloads.
Version and Environment Inventory
Before troubleshooting, gather information about your Kubernetes cluster, node networking, and the specific pod and init container. This section covers the essential commands and what to look for.
Cluster and Node Info
First, confirm the Kubernetes version and the container runtime, because networking behavior can vary between versions and CNI plugins.
kubectl version --short
Expected output (example):
Client Version: v1.27.3
Kustomize Version: v5.0.1
Server Version: v1.27.3
Check the CNI plugin in use by listing pods in the kube-system namespace:
kubectl get pods -n kube-system | grep -E 'calico|flannel|weave|cilium'
Example output:
calico-node-abcde 1/1 Running 0 5d
calico-kube-controllers-12345 1/1 Running 0 5d
If you do not see a known CNI pod, the cluster may be using a cloud provider's CNI or a custom one. Knowing the CNI is important because network policy enforcement and pod-to-pod connectivity depend on it.
Pod and Init Container Details
Describe the pod to see events and init container status:
kubectl describe pod <pod-name> -n <namespace>
Focus on the Init Containers section and the Events at the bottom. For example:
Init Containers:
init-myservice:
Container ID: containerd://...
Image: busybox:1.28
State: Terminated
Reason: Error
Exit Code: 1
Ready: False
Restart Count: 0
...
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 10m default-scheduler Successfully assigned default/myapp-pod to node-1
Warning Failed 10m kubelet Error: failed to start container "init-myservice": Error response from daemon: network plugin not ready
If the init container is in ContainerCreating or Waiting state, check the reason for delays.
Network Plugin Readiness
On the node, verify that the CNI plugin is ready. For example, with Calico, list pods in the kube-system namespace and check for pods beginning with 'calico':
kubectl get pods --namespace=kube-system
All pods should be Running and Ready. If not, the node may not have a pod network, causing init container creation to fail.
Safe Configuration Path
When configuring init containers, follow these scoped networking choices to avoid common pitfalls. Use minimal privileges and explicit network settings.
Explicit DNS Configuration
Init containers may need to resolve internal service names. By default, they inherit the pod's DNS policy. If your init container runs a command that looks up a service, ensure the DNS configuration is correct.
A common pattern is to use dnsPolicy: ClusterFirst (default) so that the init container uses the cluster DNS. If you need to override, you can set dnsConfig in the pod spec:
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
spec:
dnsPolicy: ClusterFirst
dnsConfig:
nameservers:
- 10.96.0.10
searches:
- default.svc.cluster.local
- svc.cluster.local
- cluster.local
options:
- name: ndots
value: "5"
initContainers:
- name: init-myservice
image: busybox:1.28
command: ['sh', '-c', 'nslookup my-service.default.svc.cluster.local']
containers:
- name: main
image: busybox:1.28
command: ['sleep', '3600']
This ensures the init container uses the specified DNS server and search domains. The ndots option may be necessary if you use short names.
Port and Protocol Considerations
Init containers can open ports, but they should not conflict with the main containers if they are to run concurrently. Actually, init containers run sequentially and must complete before the main containers start. They can use any port because the main containers are not yet running, but be careful if you later convert an init container to a sidecar. If you need to test connectivity to a service, the init container can make outbound connections.
If your init container needs to listen on a port for a check, use a high port to avoid conflicts. For example:
initContainers:
- name: init-check
image: busybox:1.28
command: ['sh', '-c', 'nc -l -p 8080 -e /bin/true & sleep 5']
But such listening is rarely needed; the init container is typically a client.
Network Policies
If the cluster uses NetworkPolicy, ensure that the init container is allowed to make the necessary egress connections. Network policies apply to pods, but init containers are subject to the same policy as the pod (since the pod's network namespace is shared). However, some CNI plugins may not enforce policies during init container execution. To be safe, create a policy that allows egress to the required destinations.
Example NetworkPolicy allowing egress to a specific service:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-egress-to-service
namespace: default
spec:
podSelector:
matchLabels:
app: myapp
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
app: backend
ports:
- protocol: TCP
port: 5432
Apply this policy before running the pod with the init container.
Resource Requests and Limits
Networking tools like dig, nslookup, curl, or nc may consume CPU and memory. Set appropriate resource requests and limits for the init container to avoid eviction.
initContainers:
- name: init-check
image: busybox:1.28
resources:
requests:
cpu: "100m"
memory: "64Mi"
limits:
cpu: "200m"
memory: "128Mi"
command: ['sh', '-c', 'echo checking']
Using a Minimal Base Image
Many init containers use a small image like busybox or alpine, which may lack networking tools. Install them if needed, or use a distroless image with the necessary binaries. For troubleshooting, you might temporarily use a larger image like curlimages/curl.
Verification and Diagnostics
This section provides concrete commands to verify networking from inside an init container and diagnose common issues.
Running Diagnostic Init Containers
To test connectivity, you can run a pod with an init container that performs checks and logs the output. Since init containers exit quickly, you can view logs with kubectl logs even after completion (if the container is still terminated but not garbage collected).
Example pod for DNS and connectivity tests:
apiVersion: v1
kind: Pod
metadata:
name: nettest
spec:
restartPolicy: Never
initContainers:
- name: init-dns
image: busybox:1.28
command: ['sh', '-c', 'echo "=== DNS Test ==="; nslookup kubernetes.default.svc.cluster.local; echo "=== Connectivity Test ==="; nc -zv my-service.default.svc.cluster.local 80']
containers:
- name: main
image: busybox:1.28
command: ['sleep', '10']
After the pod runs, check the init container logs:
kubectl logs nettest -c init-dns
Expected output (example):
=== DNS Test ===
Server: 10.96.0.10
Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local
Name: kubernetes.default.svc.cluster.local
Address 1: 10.96.0.1 kubernetes.default.svc.cluster.local
=== Connectivity Test ===
my-service.default.svc.cluster.local (10.96.0.100:80) open
If the DNS resolution fails, you will see an error like:
nslookup: can't resolve 'kubernetes.default.svc.cluster.local'
If the connectivity fails, you may see:
nc: connect to my-service.default.svc.cluster.local port 80 (tcp) failed: Connection refused
DNS Troubleshooting
If DNS fails, check the following:
- Check the pod's DNS configuration: Use
kubectl execinto the main container (if it is running) or inspect the pod spec. The/etc/resolv.confin the pod should have the cluster DNS IP.
kubectl exec nettest -- cat /etc/resolv.conf
Expected output:
nameserver 10.96.0.10
search default.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
- Check CoreDNS pods: Ensure CoreDNS is running and healthy.
kubectl get pods -n kube-system -l k8s-app=kube-dns
Example output:
NAME READY STATUS RESTARTS AGE
coredns-5d78c9b4f-abcde 1/1 Running 0 10d
coredns-5d78c9b4f-fghij 1/1 Running 0 10d
- Check CoreDNS logs: Look for errors or high latency.
kubectl logs -n kube-system -l k8s-app=kube-dns --tail=50
- Test DNS from another pod: Run a temporary pod with
nslookupto isolate whether the issue is specific to the init container.
kubectl run dnstest --image=busybox:1.28 --restart=Never --rm -it -- nslookup kubernetes.default
Expected:
Server: 10.96.0.10
Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local
Name: kubernetes.default
Address 1: 10.96.0.1 kubernetes.default.svc.cluster.local
Connectivity and Port Checks
If DNS works but connection fails, check the following:
- Check if the target service exists and has endpoints:
kubectl get svc my-service -o wide
Example:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
my-service ClusterIP 10.96.0.100 <none> 80/TCP 1h app=backend
Then check endpoints:
kubectl get endpoints my-service
Expected:
NAME ENDPOINTS AGE
my-service 10.244.1.5:8080 1h
If endpoints are empty, the service selector does not match any pods.
- Test connectivity from a regular pod: Use
kubectl execor run a temporary pod.
kubectl run conn-test --image=busybox:1.28 --restart=Never --rm -it -- nc -zv my-service 80
Expected if connectable:
my-service (10.96.0.100:80) open
- Check network policies: If using NetworkPolicy, ensure egress is allowed.
kubectl get networkpolicies
Review the policy details.
- Firewall on the node: If the connection is to an external IP, check if the node's firewall (e.g., iptables, security groups) is blocking. This is outside Kubernetes but can be checked via node access.
Routing Issues
Init containers may need to reach an external service. If DNS resolves but connection times out, check routing.
From inside the init container (or a temporary pod), check the route table:
kubectl exec nettest -- route -n
Example:
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 169.254.1.1 0.0.0.0 UG 0 0 0 eth0
10.244.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
The default route should point to the node's gateway. If missing, the pod cannot reach external IPs.
Also check that the CNI is functioning; a misconfigured CNI can cause routing loops or blackholes.
Capturing Traffic with tcpdump (if available)
If you have access to a pod with tcpdump, you can capture traffic during the init container execution. However, init containers often exit quickly, so you may need to add a delay to keep it running.
Example init container with a delay and tcpdump:
initContainers:
- name: init-capture
image: corfr/tcpdump
command: ['sh', '-c', 'tcpdump -i any -w /data/capture.pcap & sleep 30']
volumeMounts:
- name: data
mountPath: /data
After retrieving the pcap, analyze with Wireshark.
Common Pitfalls and Mistakes
Understanding typical missteps helps you avoid them and recover faster when they occur.
Assuming Init Containers Have Different Network Settings
Many users assume init containers can have a different DNS policy or network namespace than the main containers. In reality, they share the pod's network namespace and DNS configuration (unless overridden at the pod level). This can cause confusion when the init container behaves differently than expected.
Why it happens: The Kubernetes documentation is clear, but the mental model of sequential containers may lead one to think they are isolated.
How to avoid: Always design init containers with the same network assumptions as the main containers. If you need different DNS settings, set them explicitly in the pod spec's dnsConfig.
Overlooking Network Policies During Init Phase
Network policies may be enforced differently for init containers depending on the CNI plugin. Some CNIs enforce policies only after the pod is fully ready, which means the init container might have unrestricted egress. This can lead to false positives in testing, where the init container succeeds but the main container fails to connect due to policy restrictions.
Why it happens: The inconsistent behavior across CNIs leads to surprises.
How to avoid: Test with the same network policies you intend to apply, and verify the behavior with your specific CNI. When in doubt, explicitly allow required egress for the pod before running the init container.
Not Setting Resource Limits
Init containers without resource requests and limits can be evicted or starved, which may manifest as networking timeouts or failures. For example, a DNS lookup might time out if the container is CPU throttled.
Why it happens: Users often skip resource settings for short-lived init containers, not realizing they can still be throttled.
How to avoid: Always set reasonable requests and limits for init containers, especially those running network-intensive commands.
Using Minimal Images Without Necessary Tools
BusyBox and Alpine images may not include dig, nslookup, nc, or curl. Attempting to run them results in "command not found" errors, which are not networking problems but are often mistaken for them.
Why it happens: Users assume the tools are present by default.
How to avoid: Use an image that contains the tools you need, such as busybox with nslookup and nc or curlimages/curl for HTTP checks. For temporary debugging, you can install the tools in the init container command (e.g., apk add --no-cache bind-tools in Alpine).
Relying on Short Service Names Without Proper Search Domains
Using a short service name like my-service instead of the fully qualified my-service.default.svc.cluster.local can fail if the ndots option is misconfigured or search domains are not set. The resolver may append the wrong search domains and fail to resolve.
Why it happens: The default ndots:5 might cause unnecessary lookups, or the search domains might be missing.
How to avoid: Use fully qualified domain names in init container commands to avoid ambiguity. If short names are required, explicitly configure dnsConfig with the correct search domains and ndots value.
Assuming the Init Container Can Reach External Services Without Egress Rules
In clusters with restrictive egress policies, init containers cannot reach external endpoints (e.g., database as a service, object storage) unless explicitly allowed.
Why it happens: Users forget that egress restrictions apply to all containers in the pod, including init containers.
How to avoid: Define egress NetworkPolicies for the pod or namespace that include the necessary destinations. Test egress from the init container early in development.
Failure Modes and Recovery
Understanding common failure modes helps you quickly recover and prevent future issues.
Failure Mode 1: DNS Resolution Failure
Symptoms: Init container logs show nslookup: can't resolve, or the container exits with non-zero code.
Possible causes:
- CoreDNS not running or unreachable
- Pod DNS configuration incorrect
- Network policy blocking DNS (UDP/TCP port 53)
ndotsmisconfiguration causing excessive search domain lookups
Recovery:
- Verify CoreDNS pods are running.
- Check the pod's
/etc/resolv.confand correct if needed viadnsConfig. - Ensure NetworkPolicy allows egress to kube-dns service on port 53.
- Temporarily set
ndots:1to reduce search domain ambiguity.
After fixing, delete the pod and recreate.
Failure Mode 2: Connection Refused or Timeout
Symptoms: nc or curl reports Connection refused or timeout.
Possible causes:
- Target service has no ready endpoints
- Target pod not listening on the expected port
- NetworkPolicy denying traffic
- Firewall (iptables or cloud security group) blocking
- Routing misconfiguration
Recovery:
- Check service endpoints:
kubectl get endpoints <svc> - Check target pod readiness and port:
kubectl get pods -l app=backendandkubectl exec <target-pod> -- netstat -tulpn(if possible) - Review NetworkPolicies and adjust
- Check node firewall rules and cloud security groups
- Verify route table inside pod and on node
Failure Mode 3: Init Container Stuck in ContainerCreating
Symptoms: kubectl describe pod shows ContainerCreating for init container and an event like "network plugin not ready" or "failed to set up network".
Possible causes:
- CNI plugin not ready on the node
- CNI configuration missing or invalid
- Resource constraints preventing network setup
Recovery:
- Check CNI pods on the node:
kubectl get pods -n kube-system -o wide | grep <node-name> - Restart the CNI pod if unhealthy
- Check node's CNI configuration files in
/etc/cni/net.d/ - If using a cloud provider, verify the node's network interfaces
Failure Mode 4: Init Container Exits Too Quickly for Diagnosis
Symptoms: The init container fails and restarts rapidly, making it hard to inspect.
Recovery: Add a temporary sleep to the init container command to keep it alive, then use kubectl exec (if possible) or kubectl logs. Alternatively, run a debug container with the same network settings.
Example:
initContainers:
- name: init-debug
image: busybox:1.28
command: ['sh', '-c', 'echo starting; sleep 300']
Then while it is sleeping, exec into it:
kubectl exec -it <pod-name> -c init-debug -- sh
Rollback and Controlled Recovery
If a new init container configuration causes failures, you can roll back by:
- Reverting the pod spec changes in your deployment manifest
- Applying the previous working version with
kubectl apply -f previous.yaml - If using a Deployment, use
kubectl rollout undo deployment/<name>to revert to the last known good revision.
Always test changes in a non-production namespace first.
Operations Checklist with Ownership and Review Cadence
Use this checklist to systematically troubleshoot init container networking issues. Each item includes an accountable owner and review frequency.
| Step | Action | Command or Check | Expected Result | Owner | Review Cadence |
|---|---|---|---|---|---|
| 1 | Verify cluster and CNI health | kubectl get nodes, kubectl get pods -n kube-system | All nodes Ready, CNI pods Running | Platform Engineer (e.g., Priya Shah) | Weekly |
| 2 | Describe the pod | kubectl describe pod <pod> | Init container state with reason | Application Developer (e.g., Alex Chen) | Per incident |
| 3 | Check init container logs | kubectl logs <pod> -c <init-container> | Logs show success or error | Application Developer | Per incident |
| 4 | Test DNS resolution | Run a test pod with nslookup | Service name resolves to ClusterIP | Application Developer | Per incident |
| 5 | Verify DNS server config | kubectl exec <pod> -- cat /etc/resolv.conf | Nameserver = cluster DNS IP (e.g., 10.96.0.10) | Platform Engineer | Monthly audit |
| 6 | Check service and endpoints | kubectl get svc <svc> -o wide, kubectl get endpoints <svc> | Endpoints list matches ready pods | Application Developer | Per incident |
| 7 | Test connectivity | kubectl run test --image=busybox -- nc -zv <svc> <port> | Connection successful (open) | Application Developer | Per incident |
| 8 | Review network policies | kubectl get networkpolicies -A | Policies allow required egress | Security Engineer (e.g., Maria Garcia) | Quarterly |
| 9 | Inspect firewall and routing | On node: iptables -L, route -n | No blocks, default route exists | Platform Engineer | Monthly |
| 10 | Reproduce with debug container | Add sleep, exec into container | Environment matches failing init container | Application Developer | Per incident |
After resolving the issue, update your pod specifications and documentation. Run the checks again to confirm.
Conclusion
Networking issues in Kubernetes init containers can be challenging because they occur before the main application starts and often leave limited logs. By following the structured approach in this guide, you can systematically identify and fix DNS, connectivity, port, and routing problems.
Key takeaways:
- Init containers share the pod's network namespace, so they have the same IP and DNS configuration.
- Use explicit DNS settings and minimal network policies to avoid surprises.
- Always test with a temporary diagnostic pod or init container with the same network context.
- Check CoreDNS, service endpoints, network policies, and node firewalls in that order.
- Keep a rollback plan and test changes in a staging environment.
As a next step, apply these techniques to a real failing pod in your cluster or create a deliberate failure scenario to practice. Document your findings and update your runbooks to reduce mean time to resolution for future incidents.
Remember, the first useful pilot should be narrow, measurable, and easy to inspect locally before deployment. Start with one suspected issue, such as DNS, and expand from there. With these practical examples and commands, you can confidently troubleshoot init container networking and keep your Kubernetes workloads running smoothly.