bash regular expressions to get docker container port number

So I’m trying to get a specific port number from my docker cluster, this is done because I need the port later on.

When I do docker-compose ps I get the following output

  • How to share enviroment variables in docker
  • Docker ignores local project
  • DevOps: automatically restarting a failed container
  • How to link one docker container with another docker container
  • Forward host port to docker container
  • How can I know which docker will restart after docker daemon restarts
  • contaimer_db_1   mysqld      Up      3306/tcp
    container_node_1          /usr/bin/supervisord -n          Up>3902/tcp
    container_php_1           docker-php-entrypoint php-fpm    Up      9000/tcp
    container_redis_1 redis ...   Up      6379/tcp

    What I would like to get is the port number just from the container_node_1 3902

    So far I got

    docker-compose ps | grep "[ :]\?[[:digit:]]\{4\}"

    But this will get all ports since they have 4 numbers in a row. How would I change this to make sure it will only get the node port?

    If it’s any help, the node container will always show up as>1234

  • How to run etcd cluster in docker using ansible?
  • What is the difference between docker Swarm and Swarm mode?
  • Searching for the most optimal solution with Django, Docker, virtualenv and structure of files [closed]
  • How to clean Docker container logs?
  • docker add “requires at least one argument” error
  • Two WordPress Containers on Kitematic
  • 2 Solutions collect form web for “bash regular expressions to get docker container port number”

    Using Awk alone and calling split() function twice,

    docker-compose ps | awk '$1=="container_node_1"{n=split($NF,arr1,"->"); split(arr1[n],arr2,"/"); print arr2[1]}'

    will give you the port number as intended. This will work on any POSIX compliant Awk installed.

    If you have GNU Awk installed, you can use its gensub() function to do the regex match and extract the port number,

    docker-compose ps | awk '$1=="container_node_1"{print gensub(/.*->([[:digit:]]+)\/(.+)$/,"\\1","g",$NF)}'

    RegEx Demo for the regex used inside.

    I would rather use docker inspect


    docker-compose ps

    Name Command State Ports

    dockerpartkeepr_database_1 mysqld Up 3306/tcp
    dockerpartkeepr_partkeepr_1 docker-php-entrypoint apac … Up>80/tcp

    So I will try to get the port linked to 80

    docker inspect --format '{{ (index (index .NetworkSettings.Ports "80/tcp") 0).HostPort }}' dockerpartkeepr_partkeepr_1

    which will show


    see my answer How to get ENV variable when doing Docker Inspect

    for more explanations

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.