从容器内连接到mongoDB会话

I'm new to learning how to use goLang to build microservices. I had a whole project up and running locally, but when I tried deploying it I ran into a problem. The session I was working with (mgo.Dial("localhost")) was no longer working. When I put this into a docker image, it failed to connect to the local host, which makes sense, since the docker image builds it over a new OS (alpine in my case). I was wondering what I should do to get it to connect.

To be clear, when I was researching this, most people wanted to connect to a mongoDB session that is a docker container, I want to connect to a mongoDB session from within a docker container. Also once I'm ready for deployment I'll be using StatefulSet with kubernetes if that changes anything.

For example, this is what I want my program to be like:

sess, err := mgo.Dial("localhost") //or whatever
if err != nil {
   fmt.Println("failed to connect")
else {
   fmt.Println("connected")

What I tried doing: Dockerfile:

FROM alpine:3.6

COPY /build/app /bin/
EXPOSE 8080

ENTRYPOINT ["/bin/app"]

In terminal:

docker build -t hell:4 .
docker run -d -p 8080:8080 hell:4

And as you can expect, it says not connected. Also the port mapping is for the rest of the project, not this part.

Thanks for your help!

If your mongoDB server is running in your host machine, replace localhost by you host IP.

I think you should not try to connect to the MongoDB server running on your machine. Think about deploying the whole application lateron you want a MongoDB server running together with your service on some cloud or server.

That problem could be solved by setting up an additional container and link it to your Go Web App. Docker compose can handle this. Just place a docker-compose.yml file in the directory you are executing your docker build in.

version: '3'
  services:
    myapp:
      build: .
      image: hell:4
      ports:
        - 8080:8080
      links:
        - mongodb
      depends_on:
        - mongodb
  mongodb:
    image: mongo:latest
    ports:
        - "27017:27017"
    environment:
        - MONGODB_USER="user" 
        - MONGODB_PASS="pass"

Something like this should do it (not tested). You have two services: One for your app that gets build according to your Dockerfile in the directory in which you currently are. Additionally it links to a service called mongodb defined below. The mongodb service is accessible via the service name mongodb.