如何在特定端口运行Mongo Docker实例。

huangapple go评论69阅读模式
英文:

How to run mongo docker instance at specific port

问题

It seems like your backend application is encountering a connection error when trying to connect to the MongoDB container running on port 27018. You've verified that the MongoDB container is indeed running on that port with the IP address 172.18.0.21.

Here are a few things to check:

  1. Container Networking: Ensure that your backend application container is on the same Docker network as the MongoDB container. It looks like they both use the default network (root_default), but double-check to confirm this.

  2. DB_HOST Environment Variable: Ensure that the DB_HOST environment variable in your backend application is correctly set to mongo:27018. The hostname "mongo" corresponds to the service name in the Docker Compose file.

  3. Firewall Rules: Check if there are any firewall rules or network restrictions that might be preventing the backend container from connecting to the MongoDB container.

  4. MongoDB Authentication: If MongoDB requires authentication, make sure you've set the necessary credentials and that your backend application is using them to connect.

  5. Error Handling: Your error message indicates "ECONNREFUSED." This typically means that the connection to the specified IP and port is being refused. Make sure there are no typos or issues with IP addresses, ports, or container names.

Double-check these aspects to troubleshoot the connection error. If the issue persists, please provide more details on your Docker Compose setup and any relevant authentication settings for MongoDB so that I can offer more specific assistance.

英文:

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?

答案1

得分: 2

如果您尝试从在相同的docker-compose.yml文件中启动的容器内访问您的mongodb实例,仍然使用端口27017进行设置。

要使用端口27018,您应该添加

  command: --port 27018

到mongo服务的定义中。

然后,发布的端口将是'27018:27018'。但是,如果您不需要从外部访问mongodb(例如mongosh或UI),则可以完全省略发布的端口。您甚至可以在内部保留端口27017。

英文:

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

  command: --port 27018

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.

答案2

得分: 0

以下是翻译好的内容:

"Is depends where the backend application is running."

"Your mongo db is available on 2 locations:

  1. On the host on port 27018
  2. On the Mongo container on host 'mongo' on port 27017.

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'."

英文:

Is depends where the backend application is running.

Your mongo db is available on 2 locations:

  1. On the host on port 27018
  2. On the Mongo container on host 'mongo' on port 27017.

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'.

huangapple
  • 本文由 发表于 2023年4月13日 15:28:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定