When a compose file only lists a container port, Docker picks a free port on the host. docker compose port tells you which one it chose.
Take a service with this in its file:
services:
web:
image: nginx:stable
ports:
- "80"
Then ask Compose for the mapping of container port 80:
docker compose port web 80
It prints the address and host port, something like 0.0.0.0:49153. Leave out the port number and it lists every mapping of the service. It takes the service name, so you do not need the generated container name.
--index picks the container when a service has several replicas, and --protocol switches from tcp, the default, to udp. The output is easy to use in a script, for example to build a URL for a health check. The numbers are host ports, which is what you type in a browser or a bookmark.
Caveats: a random port changes whenever the container is recreated, so do not write it into other config. If you need a number that stays put, publish a fixed one such as "8080:80". And a service that is not running has nothing to report, so check docker compose ps first.
Further reading: docker compose port