Connect to a Nest.js server inside a docker container - docker

I'm trying to create a container for a Nest.js server. For now,I only have the basic version of the server that creates automatically when you create a Nest project. I tried some things in Dockerfile and docker-compose, but when I start the container and go to browser to localhost:3042 it says the page isn't working, but it should GET an object.
So right now, my Dockerfile looks like this:
FROM node:10
WORKDIR /microservices
COPY package*.json ./
COPY tsconfig.json tsconfig.json
COPY src src
RUN ["npm","install","global","#nestjs/cli"]
RUN ["npm", "install"]
EXPOSE 3042
ENTRYPOINT ["npm","run","start"]
And my docker-compose.yaml looks like this:
version: "3.2"
services:
server:
container_name: server
hostname: localhost
build: ./
ports:
- "3042:3042"
I run docker-compose up, go to browser and it doesn't work.
The output of the docker-compose up command is:
server | [Nest] 18 - 07/12/2019, 1:44 PM [NestFactory] Starting Nest application...
server | [Nest] 18 - 07/12/2019, 1:44 PM [InstanceLoader] AppModule dependencies initialized +26ms
server | [Nest] 18 - 07/12/2019, 1:44 PM [RoutesResolver] AppController {/}: +10ms
server | [Nest] 18 - 07/12/2019, 1:44 PM [RouterExplorer] Mapped {/, GET} route +7ms
server | [Nest] 18 - 07/12/2019, 1:44 PM [NestApplication] Nest application successfully started +5ms
So it seems like inside something is going on and the app starts successfully.
I looked on some examples, the one from their documentation where python is used and another example with Express.js, but didn't help me.

In my case, I was using FastifyAdapter, and it so happens that when being inside docker, you have to specify the host as "0.0.0.0" instead of localhost. The thing is, you have to add the host as a second parameter, instead of concatenate the strings:
WRONG
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
await app.listen("0.0.0.0:3000");
CORRECT
const app = await NestFactory.create(AppModule);
await app.listen(3000, "0.0.0.0");

Nest is using the port 3000 by default, so I think that's the problem. You can try to change it in the main.ts:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3042);
}
or changing your docker configuration.
Dockerfile
EXPOSE 3000/tcp
docker-compose.yml
version: "3.2"
services:
server:
container_name: server
hostname: localhost
build: ./
ports:
- 3000:3000

If anyone is having the same issue, my problem was that I added a second argument in app.listen
change it from this:
await app.listen(this.port, this.host);
to this
await app.listen(this.port);
solved my issue

Related

Serverless Offline - ECONNREFUSED Elasticmq with Docker-Compose

I am trying to work on a webscraper using the Serverless Framework that I want to be easily ran locally by users without having to install any necessary depedencies on their local machine. I am using serverless-offline-sqs with a local Elasticmq server hosted on a Docker container.
Currently, I have a docker-compose file that I run, then run serverless offline in another terminal which works well. That docker-compose.yml file looks like this:
# docker-compose.yml
version: '3'
services:
database:
image: 'mongo'
container_name: 'database'
environment:
- MONGO_INITDB_DATABASE=scraper_database
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=admin
volumes:
- ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
- ./mongo-volume:/data/db
ports:
- '27017-27019:27017-27019'
command: mongod --quiet --logpath /dev/null
sqs:
image: softwaremill/elasticmq:latest
container_name: 'sqs'
ports:
- '9324:9324'
sqs-create:
image: infrastructureascode/aws-cli:latest
container_name: 'sqs-create'
links:
- sqs
entrypoint: sh
command: ./create-queues.sh
volumes:
- ./scripts/create-queues.sh:/project/create-queues.sh:ro
environment:
- AWS_ACCESS_KEY_ID=local
- AWS_SECRET_ACCESS_KEY=local
- AWS_DEFAULT_REGION=eu-east-1
- AWS_ENDPOINT_URL=http://sqs:9324
This works well with no issues, and after ensuring that all of my containers are up, I can run serverless offline and my app works. I am trying to also include the act of running Serverless in its own docker container. I have created the following Dockerfile:
# Dockerfile
FROM node:12
RUN npm --loglevel=error install -g serverless && npm --loglevel=error install -g serverless-offline
WORKDIR /usr/src/app
COPY package*.json ./
COPY ./scripts/wait-for-it.sh ./
RUN ["chmod", "+x", "/usr/src/app/wait-for-it.sh"]
RUN npm install
COPY . .
EXPOSE 3000
I am trying to follow the Docker documentation for affecting the start-up order, found here to ensure that my queue service is up before running this. This has led me to this docker-compose.yml:
version: '3'
services:
serverless:
container_name: 'serverless'
build:
context: .
dockerfile: Dockerfile
env_file:
- .env.development
ports:
- '3000:3000'
depends_on:
- sqs
command: ["./wait-for-it.sh", "sqs:9324", "--", "serverless", "offline"]
database:
image: 'mongo'
container_name: 'database'
environment:
- MONGO_INITDB_DATABASE=scraper_database
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=admin
volumes:
- ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
- ./mongo-volume:/data/db
ports:
- '27017-27019:27017-27019'
command: mongod --quiet --logpath /dev/null
sqs:
image: softwaremill/elasticmq:latest
container_name: 'sqs'
ports:
- '9324:9324'
sqs-create:
image: infrastructureascode/aws-cli:latest
container_name: 'sqs-create'
links:
- sqs
entrypoint: sh
command: ./create-queues.sh
volumes:
- ./scripts/create-queues.sh:/project/create-queues.sh:ro
environment:
- AWS_ACCESS_KEY_ID=local
- AWS_SECRET_ACCESS_KEY=local
- AWS_DEFAULT_REGION=eu-east-1
- AWS_ENDPOINT_URL=http://sqs:9324
I am using the wait-for-it.sh script which the Docker documentation suggests, but it says that I am getting the following error:
Successfully built 38df0769a202
Successfully tagged assessorscraper_serverless:latest
Starting sqs ... done
Starting database ... done
Recreating serverless ... done
Starting sqs-create ... done
Attaching to sqs, database, sqs-create, serverless
serverless | wait-for-it.sh: waiting 15 seconds for sqs:9324
sqs | 07:54:45.046 [main] INFO org.elasticmq.server.Main$ - Starting ElasticMQ server (1.0.0) ...
sqs | 07:54:48.133 [elasticmq-akka.actor.default-dispatcher-6] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
sqs | 07:54:51.385 [elasticmq-akka.actor.default-dispatcher-7] INFO o.e.rest.sqs.TheSQSRestServerBuilder - Started SQS rest server, bind address 0.0.0.0:9324, visible server address http://localhost:9324
sqs | 07:54:51.643 [elasticmq-akka.actor.default-dispatcher-7] INFO o.e.r.s.TheStatisticsRestServerBuilder - Started statistics rest server, bind address 0.0.0.0:9325
sqs | 07:54:51.649 [main] INFO org.elasticmq.server.Main$ - === ElasticMQ server (1.0.0) started in 8819 ms ===
serverless | wait-for-it.sh: sqs:9324 is available after 9 seconds
sqs-create | Creating queue TownQueue
sqs | 07:54:53.808 [elasticmq-akka.actor.default-dispatcher-6] INFO o.elasticmq.actor.QueueManagerActor - Creating queue QueueData(TownQueue,MillisVisibilityTimeout(30000),PT0S,PT0S,2021-01-07T07:54:53.494Z,2021-01-07T07:54:53.494Z,None,false,false,None,None,Map())
sqs-create exited with code 0
serverless | Serverless: Running "serverless" installed locally (in service node_modules)
serverless | Serverless: DOTENV: Loading environment variables from .env.development:
serverless | Serverless: - DATABASE_URL
serverless | Serverless: - ACCOUNT_ID
serverless | Serverless: - QUEUE_URL
serverless | Serverless: Deprecation warning: Starting with next major version, default value of provider.lambdaHashingVersion will be equal to "20201221"
serverless | More Info: https://www.serverless.com/framework/docs/deprecations/#LAMBDA_HASHING_VERSION_V2
serverless | Serverless: Deprecation warning: Starting with next major version, API Gateway naming will be changed from "{stage}-{service}" to "{service}-{stage}".
serverless | Set "provider.apiGateway.shouldStartNameWithService" to "true" to adapt to the new behavior now.
serverless | More Info: https://www.serverless.com/framework/docs/deprecations/#AWS_API_GATEWAY_NAME_STARTING_WITH_SERVICE
serverless | offline: Error: connect ECONNREFUSED 0.0.0.0:9324
serverless | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
serverless |
serverless | Networking Error ---------------------------------------
serverless |
serverless | Error: connect ECONNREFUSED 0.0.0.0:9324
serverless | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
serverless |
serverless | For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
serverless |
serverless | Get Support --------------------------------------------
serverless | Docs: docs.serverless.com
serverless | Bugs: github.com/serverless/serverless/issues
serverless | Issues: forum.serverless.com
serverless |
serverless | Your Environment Information ---------------------------
serverless | Operating System: linux
serverless | Node Version: 12.20.1
serverless | Framework Version: 2.17.0 (local)
serverless | Plugin Version: 4.4.1
serverless | SDK Version: 2.3.2
serverless | Components Version: 3.4.4
serverless |
Am I still getting some race condition? Any suggestions here would be much appreciated!
The problem is likely to be in ECONNREFUSED 0.0.0.0:9324. Judging by the port number it is an attempt to reach the sqs service, but the IP-address is bad. It should connect to sqs:9324 or an IP-address of that container. 0.0.0.0 means 'any IP-address' and it is usually used to bind a port. Check your serverless configuration.
Also, you can easily check if you are in a 'race condition' or not. For that simply start your services one by one using several terminals:
docker-compose up database
docker-compose up sqs
docker-compose up sqs-create
docker-compose up serverless
If you can start services one by one then it is likely you are. In this case you can add restart: on-failure property to a service. This way if a container exits with a code other than 0 - docker restarts the container.
It turns out, my issue was actually in my serverless.yml configuration. Here, I had my serverless.yml with a custom configuration as follows:
custom:
serverless-offline-sqs:
autoCreate: true # create queue if not exists
apiVersion: '2012-11-05'
endpoint: http://0.0.0.0:9324
region: us-east-1
accessKeyId: root
secretAccessKey: root
skipCacheInvalidation: false
The correct endpoint was actually `http://sqs:9324'. Everything else was correct!

Unable to forward/map port internaly in Docker-Compose

I am currently having an app with 3 different databases (it's for a test). I have the following docker image:
Dockerfile
FROM golang:1.15
WORKDIR /myapp
# Download wait for it tool.
ADD https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh /wait-for-it
RUN chmod +x /wait-for-it
and the following docker-compose.yml
version: '3.7'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
volumes:
- .:/app
command: sh -c "/wait-for-it postgres:10001 -- /wait-for-it oracle:10000 -- /wait-for-it mongodb:10002"
depends_on:
- oracle
- mongodb
- postgres
ports:
- "8080:8080"
oracle:
image: chameleon82/oracle-xe-10g:latest
ports:
- "10000:8080"
expose:
- 10000
postgres:
image: postgres:9.6-alpine
ports:
- "10001:5432"
environment:
- POSTGRES_HOST_AUTH_METHOD=trust
- POSTGRES_DB=testdb
expose:
- 10001
mongodb:
image: mongo:latest
ports:
- "10002:27017"
expose:
- 10002
The thing is, as you saw, my app listens on 8080, but so Oracle does. I know I can change my app port, but still, I would like to switch Oracle to another port. I am trying to achieve it from port mapping, but I do feel that it only works for the host machine, not for a use from within the docker-compose, am I wrong?
Think of services within a Docker Compose network (i.e. app, oracle) as distinct hosts. Each is addressable by its service name, i.e. app should refer to the oracle service by this name (oracle).
The port mapping allows you to expose (and map) service ports within a Docker Compose network to (possibly different) host ports. This is commonly because, the host has a singular dimension of port spaces (0...65535) whereas each service within the Docker Compose network has a port space. 2 services (e.g. http1 and http2) may each use port e.g. 8080 but there's only one 8080 on the host and so, to expose each of these services on your host, one would have to yield; one could also be on the host's 8080 but the other would need to be elsewhere, perhaps 8081.
In your case, e.g. oracle runs on 8080 within the Docker Compose network and is exposed on the host's port 10000. As far as the app service is concerned, this service is available as oracle:8080 (8080 not 10000) within the Docker Compose network.
The expose syntax is purely documentary and has no functional effect.
Responding to comments
If I run your Compose script as-is, it does not work. This is expected because e.g. postgres is available on 5432 within the Compose network not on 10001
docker-compose logs app
Attaching to 63690852_app_1
app_1 | wait-for-it: waiting 15 seconds for postgres:10001
app_1 | wait-for-it: timeout occurred after waiting 15 seconds for postgres:10001
app_1 | wait-for-it: waiting 15 seconds for oracle:10000
app_1 | wait-for-it: timeout occurred after waiting 15 seconds for oracle:10000
app_1 | wait-for-it: waiting 15 seconds for mongodb:10002
app_1 | wait-for-it: timeout occurred after waiting 15 seconds for mongodb:10002
If I correct the ports:
command: sh -c "/wait-for-it postgres:5432 -- /wait-for-it oracle:8080 -- /wait-for-it mongodb:27017"
It works as expected:
docker-compose logs app
Attaching to 63690852_app_1
app_1 | wait-for-it: waiting 15 seconds for postgres:5432
app_1 | wait-for-it: postgres:5432 is available after 0 seconds
app_1 | wait-for-it: waiting 15 seconds for oracle:8080
app_1 | wait-for-it: oracle:8080 is available after 8 seconds
app_1 | wait-for-it: waiting 15 seconds for mongodb:27017
app_1 | wait-for-it: mongodb:27017 is available after 0 seconds

Can't hit dotnet core endpoint when publishing to docker

I've been working on this for awhile and can't seem to get a proper docker setup for my dotnet core application. It works fine when running with dotnet run. Here is my docker file, docker compose file, controller file, and app logs after running docker-compose up.
DockerFile:
# build application
FROM microsoft/dotnet:sdk AS build-env
WORKDIR /app
COPY ./ ./
RUN dotnet restore
RUN dotnet publish -c Release
# run application
FROM microsoft/dotnet:aspnetcore-runtime
WORKDIR /app
COPY --from=build-env app/bin/Release/netcoreapp2.2/publish/ /app
COPY appsettings.json /app
EXPOSE 80
EXPOSE 5000
ENTRYPOINT ["dotnet", "imdb_id_retrieval.dll"]
docker-compose.yml:
version: '3.7'
volumes:
imdb_id_service_volume:
external:
name: imdb_id_service_volume
networks:
app_network:
driver: bridge
services:
postgres_imdb_id_db:
image: postgres
ports:
- "5432:5432"
volumes:
- imdb_id_service_volume:/var/lib/postgresql/data
networks:
- app_network
docker_imdb_id_service:
image: docker_retrieve_data
depends_on:
- "postgres_imdb_id_db"
restart: always
environment:
- ASPNETCORE_ENVIRONMENT=development
build:
context: .
dockerfile: Dockerfile
networks:
- app_network
ports:
- "5000:80"
Controller:
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using imdb_data_retrieval.Logic;
namespace imdb_data_retrieval.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ImdbIdController : ControllerBase
{
private IRetrieveImdbIdService _retrieveImdbIdService;
public ImdbIdController(IRetrieveImdbIdService retrieveImdbIdService){
_retrieveImdbIdService = retrieveImdbIdService;
}
// GET api/values
[HttpGet]
public async Task<ActionResult<string>> Get(string title, string releaseYear)
{
var imdbId = await _retrieveImdbIdService.ScrapeImdbIdAsync(title, releaseYear);
if (imdbId == Constants.InvalidYearResponse)
return BadRequest(Constants.InvalidYearResponse);
if (imdbId == null)
return NotFound(Constants.MovieWasNotFoundResponse);
return Ok(imdbId);
}
}
}
So at this point I run "docker-compose build" and then "docker-compose up". This is the output:
[user#user-pc imdb_id_retrieval]$ docker-compose up
Starting imdb_id_retrieval_postgres_imdb_id_db_1 ... done
Recreating imdb_id_retrieval_docker_imdb_id_service_1 ... done
Attaching to imdb_id_retrieval_postgres_imdb_id_db_1, imdb_id_retrieval_docker_imdb_id_service_1
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.035 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.035 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.112 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.267 UTC [23] LOG: database system was shut down at 2019-05-12 12:37:12 UTC
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.555 UTC [1] LOG: database system is ready to accept connections
docker_imdb_id_service_1 | derp
docker_imdb_id_service_1 | host=postgres_imdb_id_db; Username=postgres; Port=5432; Database=ImdbIds;
docker_imdb_id_service_1 | warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
docker_imdb_id_service_1 | No XML encryptor configured. Key {964dd0aa-58de-4714-b544-3c48e2b80bb9} may be persisted to storage in unencrypted form.
docker_imdb_id_service_1 | Hosting environment: development
docker_imdb_id_service_1 | Content root path: /app
docker_imdb_id_service_1 | Now listening on: http://[::]:80
docker_imdb_id_service_1 | Application started. Press Ctrl+C to shut down.
Now I go to my browser and go to "http://localhost:5000/api/imdbid?title=iron%20man&releaseYear=2008" and I get a 404 response. The first time I try to hit the endpoint I see
docker_imdb_id_service_1 | warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
docker_imdb_id_service_1 | Failed to determine the https port for redirect.
And then no logs on consecutive hits. I don't think I need https configured.
Any ideas on what I'm doing wrong?
EDIT:
My Dockerfile now looks likes this.
# build application
FROM microsoft/dotnet:sdk AS build-env
WORKDIR /app
COPY ./ ./
RUN dotnet restore
RUN dotnet publish -c Release
# run application
FROM microsoft/dotnet:aspnetcore-runtime
WORKDIR /app
COPY --from=build-env app/bin/Release/netcoreapp2.2/publish/ /app
COPY appsettings.json /app
EXPOSE 80
EXPOSE 5000
# changed this
ENTRYPOINT ["dotnet", "imdb_id_retrieval.dll", "--urls", "http://0.0.0.0:5000"]

Why the volume folder is empty after a redis save?

Code
I'm trying to run a redis service defined inside a docker-compose.yml as follows:
version: '3'
services:
redis:
image: "redis:5-alpine"
volumes:
- ./redis-vol:/home/data
app:
build: .
ports:
- 8080:8080
volumes:
- .:/home/app/
This is the Dockerfile:
FROM python:2.7-alpine3.8
WORKDIR /home/app
COPY ./requirements.txt .
RUN apk add python2-dev build-base linux-headers pcre-dev && \
pip install -r requirements.txt
# Source files
COPY ./api.py .
COPY ./conf.ini .
CMD ["uwsgi", "--ini", "conf.ini"]
The app consists of this snippet running a uwsgi interface on port 8080
import uwsgi
import redis
r = redis.Redis('redis')
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
r.append('hello', 'world!')
r.save()
return [b"Hello World"]
And this is the conf.ini file:
[uwsgi]
http = :8080
wsgi-file = api.py
master = true
process = 2
enable-threads = true
uid = 1001
gid = 1001
The app service is supposed to save a key:value pair through redis every time it receives a request to http://localhost:8080.
Upon a successful request, the docker-compose process returns the following log:
redis_1_bdf757fbb2bf | 1:M 26 Nov 2018 15:38:20.399 * DB saved on disk
app_1_5f729e6bcd36 | [pid: 17|app: 0|req: 1/1] 172.21.0.1 () {38 vars in 690 bytes} [Mon Nov 26 15:38:20 2018] GET / => generated 11 bytes in 8 msecs (HTTP/1.1 200) 1 headers in 44 bytes (1 switches on core 0)
redis_1_bdf757fbb2bf | 1:M 26 Nov 2018 15:38:20.998 * DB saved on disk
app_1_5f729e6bcd36 | [pid: 17|app: 0|req: 2/2] 172.21.0.1 () {40 vars in 691 bytes} [Mon Nov 26 15:38:20 2018] GET /favicon.ico => generated 11 bytes in 4 msecs (HTTP/1.1 200) 1 headers in 44 bytes (1 switches on core 0)
Problem
Despite the DB saved on disk log, the redis_vol folder is empty and the dump.rdb file doesn't seem to be saved anywhere else.
What I am doing wrong? I've also tried to use redis:alpine as image but I have the following error at startup:
redis_1_bdf757fbb2bf | 1:M 26 Nov 14:57:27.003 # Can't handle RDB format version 9
redis_1_bdf757fbb2bf | 1:M 26 Nov 14:57:27.003 # Fatal error loading the DB: Invalid argument. Exiting.
And I've also tried to map the dump.rdb in the redis service as follows:
redis:
image: "redis:5-alpine"
volumes:
- ./redis-vol/dump.rdb:/home/data/dump.rdb
but the docker creates a folder named dump.rdb/ instead of a readable file.
If you still face the problem even after changing the volume map to
<your-volume>:/data
Make sure to delete the previous container with
docker container prune
before restarting your container again
Accoring to the redis documentation on the DockerHub page
If persistence is enabled, data is stored in the VOLUME /data
So you are using the wrong volume path. Yout should use /data instead
volumes:
- ./redis-vol:/data
To be able to mount a single file for your container with docker-compose, use absolute path of the file you want to mount from your filesystem:
redis:
image: "redis:5-alpine"
volumes:
- /Users/username/dirname/redis-vol/dump.rdb:/home/data/dump.rdb
As codestation correctly pointed out, it is on the
official documenation but he is suggesting
mount point instead of volumes which has some additional cons.
In both cases in documentation there is also statement about "persistence
enabled":
$ docker run --name some-redis -d redis redis-server --appendonly yes
or in your docker-compose file:
redis:
image: "redis:alpine"
command: redis-server --appendonly yes
volumes:
- your-volume:/data

Docker with Mongo and Express

First of all, give thanks for reading my question and try to help me and apologize for my English.
I'm trying to run a docker with a express server project and mongo, but build Dockerfile perfectly but I do:
docker logs -f name
and show next error:
/usr/local/bin/docker-entrypoint-sh line 340: exec: npm not found
And, I think that mongodb doesnt run
Why doesnt recognize npm if I add node?
How can run npm and launch mongo?
I'm using ubuntu 17.10
Here is my Dockerfile:
# Install Node
FROM node:latest
# Install Mongo
FROM mongo:4.0.0-xenial
# Author
MAINTAINER MachineGun
# Create user Ubuntu 17.10 (64 bits)
RUN adduser --disabled-login dockeruser
# Work Directory
WORKDIR /home/expressserver
# Copy express project to docker
COPY expressserver expressserver
# Defaul user
USER dockeruser
# Config cointainer PORT:
# MongoDB listening on port: 27017
# Server listening on port: 8080
EXPOSE 27017 8080
# Exec MongoDB
CMD [mongo]
# Exec server with custom npm start
CMD ["npm", "run", "start:dev"]
Also, in app.js I use mongoose with next uri: mongodb://localhost:27017/ExpressServer, its ok?
mongoose.connection.openUri('mongodb://localhost:27017/ExpressServer', { useNewUrlParser: true }, (err, res) => {
if (err) {
console.log('Error: Database not running on port 27017: \x1b[31m%s\x1b[0m', 'offline');
// console.log('throw err: ', err);
throw err;
}
console.log('Database running on port 27017: \x1b[32m%s\x1b[0m', 'online');
});
I've solved the problem :D
Thanks a lot :D
Finally I used docker compose...
Here is my docker-compose.yml:
version: '2'
services:
server:
container_name: expressserver
build: ./
ports:
- "8080:8080"
links:
- mongo
mongo:
container_name: mongoDB
image: mongo:latest
volumes:
- /var/lib/mongodb:/data/db
ports:
- "27017:27017"
command: mongod --port 27017
Here is my Dockerfile:
FROM node:carbon
MAINTAINER MachineGun
RUN adduser --disabled-login dockeruser
WORKDIR /home/dockeruser
COPY expressserver expressserver
WORKDIR /home/dockeruser/expressserver
RUN npm install
USER dockeruser
EXPOSE 8080 27017
CMD ["npm", "start"]
And in my app.js to connect with mongoose:
const options = {
autoIndex: false, // Don't build indexes
reconnectTries: 30, // Retry up to 30 times
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
// Database connection
const connectWithRetry = () => {
mongoose.connect("mongodb://mongo/expressdb", options)
.then(()=>{
console.log('Database running on port 27017: \x1b[32m%s\x1b[0m', 'online')
})
.catch( (err) => {
console.log('MongoDB connection unsuccessful on port 27017: \x1b[31m%s\x1b[0m', 'offline');
console.log('Retry after 5 seconds.');
setTimeout(connectWithRetry, 5000)
});
}
connectWithRetry();

Resources