无法使用外部 IP:Port 连接到本地数据库

我有 2 台服务器,A并且B.


它们都运行以go. 在 上Server B,我还有一个正在运行的数据库。. 中的服务器和数据库docker-containers。


docker-compose.yml


...


 userDB:

      image: mysql:oracle

      restart: always

      container_name: userDB

      environment:

        MYSQL_DATABASE: 'mydb'

        MYSQL_USER: 'user'

        MYSQL_PASSWORD: 'mypw

        MYSQL_ROOT_PASSWORD: 'myrootpw'

      cap_add:

        - SYS_NICE

      ports:

        - '3307:3306'

      networks:

        - dbnet

...



go_rest:

    build:

      context: .

      dockerfile: ./goREST/Dockerfile

    container_name: go_rest

    command: ["./goREST"]

    restart: always

    ports:

      - 8081:8081

    networks:

      - dbnet


在服务器内部,我像这样连接到数据库:


    db, err := sql.Open("mysql", "root:myrootpw@tcp(bbb.bbb.bbb.bbb:3307)/mydb")



    var usr DBUser

    stmt, _ := db.Prepare(`SELECT * from user;`)

    _ = stmt.QueryRow().Scan(&usr.SteamId)

    log.Println(*usr.SteamId)


请注意,这bbb.bbb....是我的公共 IP Server B。


现在的问题是:


Server A在(没有数据库)上运行服务器应用程序,工作正常。我还可以使用以下命令从我的开发机器连接到数据库:


ssh -L 3307:127.0.0.1:3307 usr@bbb.bbb.bbb.bbb


但是在保存数据库的机器上使用 dockerized 版本时,我无法连接到数据库?这只会发生,当在 docker 中运行时,当我像./goReston一样运行可执行文件时Server B,它也可以正常工作。我真的很困惑。


如果我的解释令人困惑:


A -----> B(docker) works

B -----> B(local) works

B -----> B(docker) doesn not work


(docker) referes to the server-application. The database is always dockerized.


操作系统:Ubuntu 20.04LTS


ITMISS
浏览 84回答 2
2回答

噜噜哒

我现在找到了解决办法。所以问题出在ufw. 我有这样的规则:3307&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ALLOW&nbsp; &nbsp; &nbsp; &nbsp;aaa.aaa.aaa.aaa3307&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ALLOW&nbsp; &nbsp; &nbsp; &nbsp;prod.local.ip.notebook3307&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ALLOW&nbsp; &nbsp; &nbsp; &nbsp;bbb.bbb.bbb.bbb这就是为什么从我的本地开发计算机(又名。prod.local.ip.notebook)访问和从server A(又名 aaa.aaa.aaa.aaa)访问有效问题是 bbb.bbb.bbb.bbb,因为带有访问数据库的 rest-API 的容器在ufw. 要允许此 IP,我必须获取容器的IP.所以我跑了:docker exec -it xyz /bin/sh,然后在容器内:ifconfig返回172.22.0.5了eth0。这是必须添加到的 IP ufw。所以我的新ufw配置如下所示:3307&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ALLOW&nbsp; &nbsp; &nbsp; &nbsp;aaa.aaa.aaa.aaa <- remote server3307&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ALLOW&nbsp; &nbsp; &nbsp; &nbsp;prod.local.ip.notebook <- development3307&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ALLOW&nbsp; &nbsp; &nbsp; &nbsp;bbb.bbb.bbb.bbb3307&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ALLOW&nbsp; &nbsp; &nbsp; &nbsp;172.22.0.5 <- container ip

慕标5832272

在 Docker 中运行时需要替换bbb.bbb.bbb.bbb:3307为。userDB:3306尝试使它成为您在运行时传递的参数,这样您就不必在使用或不使用 Docker 运行时更改代码。此外,除非您想使用某些外部工具连接到数据库,否则您不必映射端口 3306。您的 dockerized 应用程序不需要它。
打开App,查看更多内容
随时随地看视频慕课网APP