docker run mongo image on a different port
You can run processes inside a container and outside on the same port. You can even run multiple containers using the same port internally. What you can't do is map the one port from the host to a container. Or in your case, map a port that is already in use to a container.
For example, this would work on your host:
services:
webapp:
image: myimage
ports:
- '3000:3000'
mongo:
image: 'mongo:latest'
ports:
- '27018:27017'
mongo2:
image: mongo:latest
ports:
- '27019:27017'
The host mongo listens on 27017. The host also maps ports 27018 and 27019 to the container mongo instances, both listening on 27017 inside the container.
Each containers has its own network namespace and has no concept of what is running in another container or on the host.
Networks
The webapp needs to be able to connect to the mongo containers internal port. You can do this over a container network which allows connections between the container and also name resolution for each service
services:
webapp:
image: myimage
ports:
- '3000:3000'
networks:
- myapp
depends_on:
- mongo
mongo:
image: 'mongo:latest'
ports:
- '27018:27017'
networks:
- myapp
networks:
myapp:
driver: bridge
From your app the url mongo://mongo:27017
will then work.
From your host need to use the mapped port and an address on the host, which is normally localhost
: mongo://localhost:27018
You can tell MongoDB to listen on a different port in the configuration file, or by using a command-line parameter:
services:
mongo:
image: 'mongo:latest'
command: mongod --port 27018
ports:
- '27018:27018'