Docker List Container Ports

DockerDockerBeginner
Practice Now

Introduction

Imagine a scene set in the 19th century Victorian era, where participants take on the role of a Medium. The background is a mysterious Victorian mansion, and the medium's goal is to invoke spirits from the beyond by unlocking the secrets of Dockerized containers.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/ContainerOperationsGroup(["`Container Operations`"]) docker/ContainerOperationsGroup -.-> docker/port("`List Container Ports`") subgraph Lab Skills docker/port -.-> lab-271479{{"`Docker List Container Ports`"}} end

Explore the Docker Container Ports

In this step, you will start by running a Docker container and then explore its exposed ports.

First, let's run a simple Nginx container:

docker run -d -p 8080:80 --name my-nginx nginx

Now, you will inspect the ports that the container is listening on:

docker port my-nginx

The expected output should show the mapping of the container's ports to the host machine's ports.

80/tcp - > 0.0.0.0:8080
80/tcp - > :::8080

Test with a Custom Port

For this step, you will run a custom Python application inside a Docker container and expose a custom port.

Start by creating a simple Python application in a file named app.py:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, Docker!'

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

Create a Dockerfile with the following content to build an image for the Python application:

FROM python:3.8
WORKDIR /app
COPY . /app
RUN pip install flask
EXPOSE 5000
CMD ["python", "app.py"]

Now, build the Docker image run it with the custom port 5000 exposed, and map the exposed port to 8081 in the host

docker build -t my-python-app .
docker run -itd -p 8081:5000 --name python-app my-python-app

Once the container is running, test if the application is accessible by add a web service mapping on the top menu and visit the URL.

Summary

In this lab, participants were taken on a journey to explore and understand how to list container ports in Docker. By creating and inspecting Docker container ports, they gained valuable insights into the networking capabilities of Docker containers, enabling them to better manage and troubleshoot container deployments.

Other Docker Tutorials you may like