duanba7653
duanba7653
2019-06-09 12:55

无法从主机访问docker容器内的服务器

已采纳

I am hosting a mysql server and a go http server in docker. I am unable to hit the http server from my host machine. My host machine is a mac.

I have tried using localhost:8080 and ipofserver:8080. I get the ip from the docker inspect. I am able to connect to my mysql server from my host, but i can't hit the server from the host.

Here is my docker ps output.

0.0.0.0:8080->8080/tcp
0.0.0.0:3306->3306/tcp, 33060/tcp

Below are my details:

Docker Desktop version 2.0.0.3.

docker-compose

version: '3.1'

services:

    mysql:
        image: mysql:latest
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: password
            MYSQL_DATABASE: mydb
        volumes:
            - mysql:/var/lib/mysql
        ports:
            - "3306:3306"
        networks:
            - mynetwork

    server:
        image: server:latest
        networks:
             - mynetwork
        ports:
             - "8080:8080"

volumes:
    mysql: ~

networks:
    mynetwork:
        driver: "bridge"

mysql dockerfile

FROM mysql:8.0.16

COPY ./scripts/mysql/dbgen-v1.sql /docker-entrypoint-initdb.d/

EXPOSE 3306

server dockerfile

FROM golang:1.12.5

WORKDIR a/go/path
COPY . .

ENV GOBIN=/usr/local/bin

RUN go get github.com/go-sql-driver/mysql
RUN go get github.com/iancoleman/strcase
RUN go get github.com/jmoiron/sqlx
RUN go get github.com/spf13/cobra
RUN go get github.com/gorilla/websocket
RUN go get github.com/spf13/viper

RUN go install -v cmd/project/main.go

EXPOSE 8080

CMD ["main"]
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongtongjian3127 dongtongjian3127 2年前

    (This answer is based on the chat we had in the comments)

    In order to expose the web server from inside the container to the host it needs to bind to 0.0.0.0 and not to 127.0.0.1. Using 0.0.0.0 ensures that the web server binds to the bridge interface that can be accessed from the host side.

    Relevant Docker docs: https://docs.docker.com/v17.09/engine/userguide/networking/default_network/binding/

    点赞 评论 复制链接分享