How to get docker mapped ports from node.js application?

前端 未结 4 681
無奈伤痛
無奈伤痛 2021-02-06 05:44

I would like to get mapped port from inside node.js application.

ex.

docker-compose:

my-app:
    build:
        context: ./my-app
           


        
4条回答
  •  孤城傲影
    2021-02-06 06:01

    You can use docker port for this.

    docker port my-app 80
    

    That will include the listener IP. If you need to strip that off, you can do that with the shell:

    docker port my-app 80 | cut -f2 -d:
    

    Unfortunately, this will only work with access to the docker socket. I wouldn't recommend mounting that socket for just this level of access inside your container.

    Typically, most people solve this by passing a variable to their app and controlling what port is published in their docker-compose file. E.g.:

    my-app:
        build:
            context: ./my-app
        ports:
            - "8080:80"     
        environment:
            - PUBLISHED_PORT=8080
        volumes:
            - /var/run/docker.sock:/tmp/docker.sock
        networks:
            - private
    

    Then the app would look at the environment variable to reconfigure itself.

提交回复
热议问题