2

I am working on golang project, recently I read about docker and try to use docker with my app. I am using mongoDB for database. Now problem is that, I am creating Dockerfile to install all packages and compile and run the go project. I am running mongo data as locally, if I am running go program without docker it gives me output, but if I am using docker for same project (just installing dependencies with this and running project), it compile successfully but not gives any output, having error::

CreateSession: no reachable servers 

my Dockerfile::

# Start from a Debian image with the latest version of Go installed
# and a workspace (GOPATH) configured at /go.
FROM golang
WORKDIR $GOPATH/src/myapp

# Copy the local package files to the container's workspace.
ADD . /go/src/myapp

#Install dependencies
RUN go get ./...

# Build the installation command inside the container.
RUN go install myapp

# Run the outyet command by default when the container starts.
ENTRYPOINT /go/bin/myapp

# Document that the service listens on port 8080.
EXPOSE 8080
EXPOSE 27017
Archana Sharma
  • 1,953
  • 6
  • 33
  • 65

2 Answers2

9

When you run your application inside Docker, it's running in a virtual environment; It's just like another computer but everything is virtual, including the network.

To connect your container to the host, Docker gives it an special ip address and give this ip an url with the value host.docker.internal.

So, assuming that mongo is running with binding on every interface on the host machine, from the container it could be reached with the connection string:

mongodb://host.docker.internal:21017/database

Simplifying, Just use host.docker.internal as your mongodb hostname.

Renato Aquino
  • 784
  • 1
  • 5
  • 15
  • I didn't understand , can you please elaborate – Archana Sharma Sep 13 '18 at 14:13
  • I didn't add mongo container because I am using database on local machine, please suggest me is their any dependency – Archana Sharma Sep 13 '18 at 14:33
  • I am facing similar problem, this solution didn't work too, any help on this? https://stackoverflow.com/questions/66022448/how-to-load-data-in-mongodb-running-in-host-from-inside-a-docker-running-on-the – Aakash Basu Feb 03 '21 at 06:45
3

In your golang project, how do you specify connection to mongodb? localhost:27017?

If you are using localhost in your code, your docker container will be the localhost and since you don't have mongodb in the same container, you'll get the error.

If you are starting your docker with command line docker run ... add --network="host". If you are using docker-compose, add network_mode: "host"

Ideally you would setup mongodo in it's own container and connect them from your docker-compose.yml -- but that's not what you are asking for. So, I won't go into that.

In future questions, please include relevant Dockerfile, docker-compose.yml to the extent possible. It will help us give more specific answer.

Phani Kandula
  • 387
  • 2
  • 3