I pulled the ubuntu image and run the container on my windows. I want to connect my MongoDB running locally on windows with ubuntu container. How it is possible or if not what is the best practice to achieve this?
You could use docker-compose network
By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.
Let's use a Node app with MongoDB for example.
Your docker-compose file Docker compose.yaml
version: "3"
services:
app:
image: myapp:latest # your app docker image
depends_on:
- db
ports:
- 80:80
networks:
- network
environment:
- MONGO_URL=mongodb://db:27017 #MongoUrl you can use in your app to connect
db:
image: mongo:latest
volumes:
- /data/db:/data/db
ports:
- 27017:27017
networks:
- network
networks:
network:
driver: bridge
You can connect with the environment variables in Node as below
import mongoose from "mongoose"
const mongodbUrl = process.env.MONGO_URL
const mongoConnectionOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
poolSize: 10,
bufferMaxEntries: 0
}
mongoose
.connect(mongodbUrl, mongoConnectionOptions)
.then(async (db) => {
console.log(`Mongo db ${db.version} is connected`)
})
.catch((err) => {
console.log("MongoDB connection error. Please make sure MongoDB is running. " + err)
})
Then use docker-compose up
to start these 2 services
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.