This is how I setup a mongodb and a backend app using docker-compose. As I am running an old mongodb instance on port 27017
, I have to use another port. So this is how I setup for port 27018
.
Mongodb is running and I can connect using mongosh
.
version: '3.5'
services:
mongo:
container_name: mongo
image: mongo:6.0.3
restart: always
ports:
- "27018:27017"
volumes:
- /opt/mongodb/data:/data/db
api:
container_name: api
image: custom-api:latest
restart: always
ports:
- "3100:3100"
environment:
- DB_HOST=mongo:27018
The backend application (nestJS) tries to connect to the DB:
const host = process.env.DB_HOST
const mongo = 'mongodb://' + host
const options = {}
const client = new MongoClient(mongo, options)
try {
await client.connect()
return client.db(database)
} catch (error) {
console.error(error)
}
But running the backend gives me a connection error:
MongoServerSelectionError: connect ECONNREFUSED 172.18.0.21:27018
at Timeout._onTimeout (/usr/src/app/node_modules/mongodb/lib/sdam/topology.js:292:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'mongo:27018' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
I checked the mongo container and as far as can see, it is running at port 27018
and the IP address is 172.18.0.21
$ docker inspect mongo
[
{
"Id": "8f9a6d2c36a106edbcfd84ee4bc8f3c72ce1ee13f65dc59d4f593085bb1f72f1",
"Created": "2023-04-13T06:25:48.388105401Z",
"Path": "docker-entrypoint.sh",
"Args": [
"mongod"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 31483,
"ExitCode": 0,
"Error": "",
"StartedAt": "2023-04-13T06:25:49.375455874Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:0850fead9327a6d88722c27116309022d78e9daf526b407a88de09762c32e620",
"ResolvConfPath": "/var/lib/docker/containers/8f9a6d2c36a106edbcfd84ee4bc8f3c72ce1ee13f65dc59d4f593085bb1f72f1/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/8f9a6d2c36a106edbcfd84ee4bc8f3c72ce1ee13f65dc59d4f593085bb1f72f1/hostname",
"HostsPath": "/var/lib/docker/containers/8f9a6d2c36a106edbcfd84ee4bc8f3c72ce1ee13f65dc59d4f593085bb1f72f1/hosts",
"LogPath": "/var/lib/docker/containers/8f9a6d2c36a106edbcfd84ee4bc8f3c72ce1ee13f65dc59d4f593085bb1f72f1/8f9a6d2c36a106edbcfd84ee4bc8f3c72ce1ee13f65dc59d4f593085bb1f72f1-json.log",
"Name": "/mongo",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "docker-default",
"ExecIDs": null,
"HostConfig": {
"Binds": [
"/opt/mongodb/data:/data/db:rw"
],
"ContainerIDFile": "",
"NetworkMode": "root_default",
"PortBindings": {
"27017/tcp": [
{
"HostIp": "",
"HostPort": "27018"
}
]
},
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": [],
"CapAdd": null,
"CapDrop": null,
"Dns": null,
"DnsOptions": null,
"DnsSearch": null,
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "shareable",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": null,
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": null,
"DeviceCgroupRules": null,
"DiskQuota": 0,
"KernelMemory": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": 0,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0,
"MaskedPaths": [
"/proc/acpi",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/timer_list",
"/proc/timer_stats",
"/proc/sched_debug",
"/proc/scsi",
"/sys/firmware"
],
"ReadonlyPaths": [
"/proc/asound",
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger"
]
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/3c94b17a3042e1ddb44e3aae5738e26c6a486c60fa827210b9c231d099c49ba3-init/diff:/var/lib/docker/overlay2/6f4fe3c9f0ebebdf05be4238d470f4e1cf47e1dcd951827f598dfefceb83f083/diff:/var/lib/docker/overlay2/b466d85cf8ecc60e7b9d843252f7a3b93e8bd42648a9293fbd21de554475293c/diff:/var/lib/docker/overlay2/5efe3f538b14b3cd7e03bfa20b47e781f8ae23585d7534620086a3426b60d1fd/diff:/var/lib/docker/overlay2/00b32be3ac44afe3c34d11a5cae80f32a0ad042a15b7d8a9b9ea3b2ef2f912d0/diff:/var/lib/docker/overlay2/68ef703e86c29ba143e94c68bcb336ca448dfb6671c4def38fcf0fd405f39cd3/diff:/var/lib/docker/overlay2/f99e7bee906d1f6ac333d704eb409ad80b5a1800f002bb604c77eab880b4d6e7/diff:/var/lib/docker/overlay2/a953e99bfbe3db3d27fbf14181309e0883ded46509a45753d7238dd3e1bcef16/diff:/var/lib/docker/overlay2/a91c55b0aa1abb4959d98ac06ec579b1193e32715d93acf3057a877cad9ee13e/diff:/var/lib/docker/overlay2/090e8dd5fd41f1676d731f7421b0878019ff30e7653059f72143ab7af156452c/diff",
"MergedDir": "/var/lib/docker/overlay2/3c94b17a3042e1ddb44e3aae5738e26c6a486c60fa827210b9c231d099c49ba3/merged",
"UpperDir": "/var/lib/docker/overlay2/3c94b17a3042e1ddb44e3aae5738e26c6a486c60fa827210b9c231d099c49ba3/diff",
"WorkDir": "/var/lib/docker/overlay2/3c94b17a3042e1ddb44e3aae5738e26c6a486c60fa827210b9c231d099c49ba3/work"
},
"Name": "overlay2"
},
"Mounts": [
{
"Type": "bind",
"Source": "/opt/mongodb/data",
"Destination": "/data/db",
"Mode": "rw",
"RW": true,
"Propagation": "rprivate"
},
{
"Type": "volume",
"Name": "ac914c3fb835b5c7028b58825558fc109c94e30b13938548bbe520ba736adbc0",
"Source": "/var/lib/docker/volumes/ac914c3fb835b5c7028b58825558fc109c94e30b13938548bbe520ba736adbc0/_data",
"Destination": "/data/configdb",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
"Config": {
"Hostname": "8f9a6d2c36a1",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"27017/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GOSU_VERSION=1.12",
"JSYAML_VERSION=3.13.1",
"MONGO_PACKAGE=mongodb-org",
"MONGO_REPO=repo.mongodb.org",
"MONGO_MAJOR=6.0",
"MONGO_VERSION=6.0.3",
"HOME=/data/db"
],
"Cmd": [
"mongod"
],
"Image": "mongo:6.0.3",
"Volumes": {
"/data/configdb": {},
"/data/db": {}
},
"WorkingDir": "",
"Entrypoint": [
"docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {
"com.docker.compose.config-hash": "1bb0f4e8831b78bb570c3e7231260fc01cedafaedf4a8eb29808ce3c1590d21e",
"com.docker.compose.container-number": "1",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "root",
"com.docker.compose.service": "mongo",
"com.docker.compose.version": "1.22.0"
}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "80b5cd3f3b8cfed3fe015e886113ba4542962190a4b7ae05029f778d3ec579c7",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"27017/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "27018"
}
]
},
"SandboxKey": "/var/run/docker/netns/80b5cd3f3b8c",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"root_default": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"mongo",
"8f9a6d2c36a1"
],
"NetworkID": "d6b6cc90deda1a99ae078573468d434f589225a578f12a1cd867e969054ad09d",
"EndpointID": "ffac6eccb9cad4692030f0b2649b5be032ed9e0003f22628fb498d5592ce6add",
"Gateway": "172.18.0.1",
"IPAddress": "172.18.0.21",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:12:00:15",
"DriverOpts": null
}
}
}
}
]
I don’t see the mistake in the configuration. Why is there a connection error?
2
Answers
If you try to access your mongodb instance from a container started within the same docker-compose.yml it’s still port 27017 with your setup.
To use port 27018 you should add
to the mongo service definition.
Then the published ports will be ‘27018:27018’. However, if you don’t need to access mongodb from outside (mongosh or UI), you can leave out published ports at all. You might even keep 27017 internally then.
Is depends where the backend application is running.
Your mongo db is available on 2 locations:
Backend is running on the Host
In this case the backend application needs to connect to 127.0.0.1:27018.
Backend is running in another container.
This container is called ‘api’ in your docker-compose file
In this case the backend needs to connect to ‘mongo:27017’.