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
contaimer_db_1 docker-entrypoint.sh mysqld Up 3306/tcp
container_node_1 /usr/bin/supervisord -n Up 0.0.0.0:3902->3902/tcp
container_php_1 docker-php-entrypoint php-fpm Up 9000/tcp
container_redis_1 docker-entrypoint.sh 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 0.0.0.0:1234->1234
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
example
docker-compose ps
dockerpartkeepr_database_1 docker-entrypoint.sh mysqld Up 3306/tcp
dockerpartkeepr_partkeepr_1 docker-php-entrypoint apac ... Up 0.0.0.0:80->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
80
see my answer How to get ENV variable when doing Docker Inspect
for more explanations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With