How to get a Docker container's IP address from the host

后端 未结 30 2781
小鲜肉
小鲜肉 2020-11-22 08:45

Is there a command I can run to get the container\'s IP address right from the host after a new container is created?

Basically, once Docker creates the container, I

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 09:18

    I wrote the following Bash script to get a table of IP addresses from all containers running under docker-compose.

    function docker_container_names() {
        docker ps -a --format "{{.Names}}" | xargs
    }
    
    # Get the IP address of a particular container
    dip() {
        local network
        network='YOUR-NETWORK-HERE'
        docker inspect --format "{{ .NetworkSettings.Networks.$network.IPAddress }}" "$@"
    }
    
    dipall() {
        for container_name in $(docker_container_names);
        do
            local container_ip=$(dip $container_name)
            if [[ -n "$container_ip" ]]; then
                echo $(dip $container_name) " $container_name"
            fi
        done | sort -t . -k 3,3n -k 4,4n
    }
    

    You should change the variable network to your own network name.

提交回复
热议问题