<pre><code>apiVersion: v1
    kind: Pod
    metadata:
       name: echo-pod
       namespace: echo
    spec:
       containers:
       - name: nginx
         image: nginx
         ports:
            -  containerPort: 81
</code></pre>
<p>Tried to connect on port 81, by running above yaml file, but it is still connecting on port 80.
Checked connection using telnet</p>
<p>The ip of echo -pod is 192.168.211.1</p>
<h1>Able to connect echo pod  from busybox pod(which is already exists) on port 80 but not on port 81. you can observe following</h1>
<pre><code>root@ip-172-31-16-143:~# kubectl exec busybox -- telnet 192.168.211.1 80
Connected to 192.168.211.1

root@ip-172-31-16-143:~# kubectl exec busybox -- telnet 192.168.211.1 81
telnet: can't connect to remote host (192.168.211.1): Connection refused
command terminated with exit code 1
</code></pre>

<p>By defining <code>containerPort: 81</code> on your pod template, you are only changing the <a href="https://docs.docker.com/engine/reference/builder/#expose" rel="noreferrer">exposed container port</a>, but your Nginx server will still listen on port 80 (as it is configured by default).</p>
<p><strong>You need to change the Nginx <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#listen" rel="noreferrer"><code>listen</code></a> configuration to match your new exposed port</strong>.</p>
<p><em>Different from mostly docker implementations, Nginx doesn't support such configs by using environment variables (see <a href="https://hub.docker.com/_/nginx" rel="noreferrer">Using environment variables in Nginx configuration</a> on their Docker Hub page).</em></p>
<p>If you wish to adapt the Nginx default configuration, you need to create a new <code>nginx.conf</code> with the <code>listen 81;</code> config, then replace the original using <code>COPY</code> in your Dockerfile to create a custom image <code>FROM</code> nginx.</p>
<p>If your prefer an &quot;one-line workaround&quot; still using the original Nginx image, you can change the command/args to replace the listen config on every start:</p>
<pre><code>  containers:
  - name: nginx
    image: nginx
    command: [&quot;/bin/sh&quot;,&quot;-c&quot;]
    args: [&quot;sed -i 's/listen  .*/listen 81;/g' /etc/nginx/conf.d/default.conf &amp;&amp; exec nginx -g 'daemon off;'&quot;]
    ports:
    - containerPort: 81
</code></pre>
