Docker Container Failed to Run - docker

The Dockerfile for my application is as follows
# Tells the Docker which base image to start.
FROM node
# Adds files from the host file system into the Docker container.
ADD . /app
# Sets the current working directory for subsequent instructions
WORKDIR /app
RUN npm install
RUN npm install -g bower
RUN bower install --allow-root
RUN npm install -g nodemon
#expose a port to allow external access
EXPOSE 9000 9030 35729
# Start mean application
CMD ["nodemon", "server.js"]
The docker-compose.yml file is as follows
web:
build: .
links:
- db
ports:
- "9000:9000"
- "9030:9030"
- "35729:35729"
db:
image: mongo:latest
ports:
- "27017:27017"
And the error generated while running is as follows:-
web_1 | [nodemon] 1.11.0
web_1 | [nodemon] to restart at any time, enter `rs`
web_1 | [nodemon] watching: *.*
web_1 | [nodemon] starting `node server.js`
web_1 | Server running at http://127.0.0.1:9000
web_1 | Server running at https://127.0.0.1:9030
web_1 |
web_1 | /app/node_modules/mongodb/lib/server.js:261
web_1 | process.nextTick(function() { throw err; })
web_1 | ^
web_1 | MongoError: failed to connect to server [localhost:27017] on first connect
web_1 | at Pool.<anonymous> (/app/node_modules/mongodb-core/lib/topologies/server.js:313:35)
web_1 | at emitOne (events.js:96:13)
web_1 | at Pool.emit (events.js:188:7)
web_1 | at Connection.<anonymous> (/app/node_modules/mongodb-core/lib/connection/pool.js:271:12)
web_1 | at Connection.g (events.js:291:16)
web_1 | at emitTwo (events.js:106:13)
web_1 | at Connection.emit (events.js:191:7)
web_1 | at Socket.<anonymous> (/app/node_modules/mongodb-core/lib/connection/connection.js:165:49)
web_1 | at Socket.g (events.js:291:16)
web_1 | at emitOne (events.js:96:13)
web_1 | at Socket.emit (events.js:188:7)
web_1 | at emitErrorNT (net.js:1281:8)
web_1 | at _combinedTickCallback (internal/process/next_tick.js:74:11)
web_1 | at process._tickCallback (internal/process/next_tick.js:98:9)
web_1 | [nodemon] app crashed - waiting for file changes before starting...
I have uploaded the image for my application at DockerHub as crissi/airlineInsurance.

In docker you can't connect to an other container via localhost because each container is independend and has its own IP. You should use container_name:port. In your example it should be db:27017 to connect from your NodeJS application in 'web' to the MongoDB in 'db'.
So it's not the problem of your Dockerfile. It's the connection URL from your NodeJS application that points to localhost instead of db.

Related

Getting error at starting mayan "No module named 'sqlalchemy'"

I try to use the Mayan-EDMS for my project. In my Django project, I have Postgres and Redis containers so I made changes in Mayan-EDMS docker-compose.yml file to work with my Postgres and Redis. Following is the Mayan docker-compose.yaml code:
services:
app:
environment: &mayan_env
MAYAN_CELERY_BROKER_URL: redis://redis:6379/0
MAYAN_CELERY_RESULT_BACKEND: db+postgresql://username:Password123#xx.xx.xx.xx/celery
MAYAN_DATABASES: "{'default':{'ENGINE':'django.db.backends.postgresql','NAME':'mayan','PASSWORD':'Password123','USER':'username','HOST':'xx.xx.xx.xx'}}"
MAYAN_DOCKER_WAIT: "xx.xx.xx.xx:5432 redis:6379"
image: mayanedms/mayanedms:3
networks:
- abc_network
ports:
- "80:8000"
volumes:
- ${MAYAN_APP_VOLUME:-app}:/var/lib/mayan
- /opt/staging_files:/staging_fi
- /opt/watch_folder:/watch_folder
And when I do docker-compose up app I am getting an error CommandError: Error during signal_pre_upgrade signal: No module named 'sqlalchemy', <class 'ModuleNotFoundError'>. full log as follow:
abc#abc-3567:~/Desktop/mayan-edms$ docker-compose up app
Starting mayanedms_app_1 ...
Starting mayanedms_app_1 ... done
Attaching to mayanedms_app_1
app_1 | mayan: starting entrypoint.sh
app_1 | Waiting for xx.xx.xx.xx:5432
app_1 | Waiting for redis:6379
app_1 | mayan: update_uid_gid()
app_1 | usermod: no changes
app_1 | mayan: os_package_installs()
app_1 | mayan: pip_installs()
app_1 | mayan: performupgrade()
app_1 | Operations to perform:
app_1 | Apply all migrations: acls, actstream, admin, appearance, auth, authtoken, autoadmin, cabinets, checkouts, common, contenttypes, converter, django_celery_beat, django_gpg, document_comments, document_indexing, document_parsing, document_signatures, document_states, documents, dynamic_search, events, file_caching, file_metadata, linking, lock_manager, logging, mailer, mayan_statistics, metadata, motd, ocr, permissions, quotas, sessions, sites, sources, storage, tags, user_management, web_links
app_1 | Running migrations:
app_1 | No migrations to apply.
app_1 | CommandError: Error during signal_pre_upgrade signal: No module named 'sqlalchemy', <class 'ModuleNotFoundError'>
mayanedms_app_1 exited with code 1

I am getting error when I try to dockerize my MERN application

Here is my Dockerfile for React.js with the error I got in terminal:
FROM node:8
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY ./package.json /usr/src/app
RUN npm install
RUN npm build
EXPOSE 3000
CMD ["npm", "run", "start"]
Error:-
react_1 |
react_1 | > ecom-panther#0.1.0 start /usr/src/app
react_1 | > react-scripts start
react_1 |
react_1 | ℹ 「wds」: Project is running at http://172.18.0.2/
react_1 | ℹ 「wds」: webpack output is served from
react_1 | ℹ 「wds」: Content not from webpack is served from /usr/src/app/public
react_1 | ℹ 「wds」: 404s will fallback to /
react_1 | Starting the development server...
react_1 |
ecom-panther_react_1 exited with code 0
For Node and Express, I got this:
express_1 | (node:30) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
express_1 | server is running on port: 5000
express_1 | (node:30) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
express_1 | at Pool.<anonymous> (/usr/src/app/node_modules/mongodb/lib/core/topologies/server.js:438:11)
express_1 | at emitOne (events.js:116:13)
express_1 | at Pool.emit (events.js:211:7)
express_1 | at createConnection (/usr/src/app/node_modules/mongodb/lib/core/connection/pool.js:561:14)
express_1 | at connect (/usr/src/app/node_modules/mongodb/lib/core/connection/pool.js:994:11)
express_1 | at makeConnection (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:31:7)
express_1 | at callback (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:264:5)
express_1 | at Socket.err (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:294:7)
express_1 | at Object.onceWrapper (events.js:315:30)
express_1 | at emitOne (events.js:116:13)
express_1 | at Socket.emit (events.js:211:7)
express_1 | at emitErrorNT (internal/streams/destroy.js:73:8)
express_1 | at _combinedTickCallback (internal/process/next_tick.js:139:11)
express_1 | at process._tickCallback (internal/process/next_tick.js:181:9)
express_1 | (node:30) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
express_1 | (node:30) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Docker file for backend:-
FROM node:8
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app
RUN npm install
COPY . /usr/src/app
EXPOSE 5000
CMD ["npm","start"]
Here is my docker-compose.yml file
version: '3' # specify docker-compose version
# Define the service/container to be run
services:
react: #name of first service
build: client #specify the directory of docker file
ports:
- "3000:3000" #specify port mapping
express: #name of second service
build: server #specify the directory of docker file
ports:
- "5000:5000" #specify port mapping
links:
- database #link this service to the database service
database: #name of third service
image: mongo #specify image to build contasiner flow
ports:
- "27017:27017" #specify port mapping
How I can run frontend at browser and is there any easy approach to do this in a better way ?
Error 1:
Add stdin_open: true to your react service, like:
...
services:
react: #name of first service
build: client #specify the directory of docker file
stdin_open: true
ports:
- "3000:3000" #specify port mapping
...
You might need to rebuild or clean cached so "docker-compose up --build" or "docker-compose build --no-cache" then "docker-compose up"
Error 2:
In your database connections line in your index.js file or whatever you named should have :
mongodb://database:27017/
where "database" is your named MongoDB service. You can use your container IP address too with docker inspect <container> and use the IP the see there too. Ideally you want to have a ENV in your Dockerfile or docker-compose.yml:
ENV MONGO_URL mongodb://database:27017/

Docker - Celery cannot connect to redis

Project structure:
client
nginx
web/
celery_worker.py
project
config.py
api/
I have the following services in my docker-compose:
version: '3.6'
services:
web:
build:
context: ./services/web
dockerfile: Dockerfile-dev
volumes:
- './services/web:/usr/src/app'
ports:
- 5001:5000
environment:
- FLASK_ENV=development
- APP_SETTINGS=project.config.DevelopmentConfig
- DATABASE_URL=postgres://postgres:postgres#web-db:5432/web_dev
- DATABASE_TEST_URL=postgres://postgres:postgres#web-db:5432/web_test
- SECRET_KEY=my_precious
depends_on:
- web-db
- redis
celery:
image: dev3_web
restart: always
volumes:
- ./services/web:/usr/src/app
- ./services/web/logs:/usr/src/app
command: celery worker -A celery_worker.celery --loglevel=INFO -Q cache
environment:
- CELERY_BROKER=redis://redis:6379/0
- CELERY_RESULT_BACKEND=redis://redis:6379/0
depends_on:
- web
- redis
links:
- redis:redis
redis:
image: redis:5.0.3-alpine
restart: always
expose:
- '6379'
ports:
- '6379:6379'
monitor:
image: dev3_web
ports:
- 5555:5555
command: flower -A celery_worker.celery --port=5555 --broker=redis://redis:6379/0
depends_on:
- web
- redis
web-db:
build:
context: ./services/web/project/db
dockerfile: Dockerfile
ports:
- 5435:5432
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
nginx:
build:
context: ./services/nginx
dockerfile: Dockerfile-dev
restart: always
ports:
- 80:80
- 8888:8888
depends_on:
- web
- client
- redis
client:
build:
context: ./services/client
dockerfile: Dockerfile-dev
volumes:
- './services/client:/usr/src/app'
- '/usr/src/app/node_modules'
ports:
- 3007:3000
environment:
- NODE_ENV=development
- REACT_APP_WEB_SERVICE_URL=${REACT_APP_WEB_SERVICE_URL}
depends_on:
- web
- redis
CELERY LOG
However, celery is not being able to connect, from this log:
celery_1 | [2019-03-29 03:09:32,111: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 99 connecting to localhost:6379. Address not available..
celery_1 | Trying again in 2.00 seconds...
WEB LOG
and so is not web service (running the backend), by the same log:
web_1 | Waiting for postgres...
web_1 | PostgreSQL started
web_1 | * Environment: development
web_1 | * Debug mode: on
web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
web_1 | * Restarting with stat
web_1 | * Debugger is active!
web_1 | * Debugger PIN: 316-641-271
web_1 | 172.21.0.9 - - [29/Mar/2019 03:03:17] "GET /users HTTP/1.0" 200 -
web_1 | 172.21.0.9 - - [29/Mar/2019 03:03:26] "POST /auth/register HTTP/1.0" 500 -
web_1 | Traceback (most recent call last):
web_1 | File "/usr/lib/python3.6/site-packages/redis/connection.py", line 492, in connect
web_1 | sock = self._connect()
web_1 | File "/usr/lib/python3.6/site-packages/redis/connection.py", line 550, in _connect
web_1 | raise err
web_1 | File "/usr/lib/python3.6/site-packages/redis/connection.py", line 538, in _connect
web_1 | sock.connect(socket_address)
web_1 | OSError: [Errno 99] Address not available
web_1 |
web_1 | During handling of the above exception, another exception occurred:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/lib/python3.6/site-packages/kombu/connection.py", line 431, in _reraise_as_library_errors
web_1 | yield
web_1 | File "/usr/lib/python3.6/site-packages/celery/app/base.py", line 744, in send_task
web_1 | self.backend.on_task_call(P, task_id)
web_1 | File "/usr/lib/python3.6/site-packages/celery/backends/redis.py", line 265, in on_task_call
web_1 | self.result_consumer.consume_from(task_id)
web_1 | File "/usr/lib/python3.6/site-packages/celery/backends/redis.py", line 125, in consume_from
web_1 | return self.start(task_id)
web_1 | File "/usr/lib/python3.6/site-packages/celery/backends/redis.py", line 107, in start
web_1 | self._consume_from(initial_task_id)
web_1 | File "/usr/lib/python3.6/site-packages/celery/backends/redis.py", line 132, in _consume_from
web_1 | self._pubsub.subscribe(key)
web_1 | File "/usr/lib/python3.6/site-packages/redis/client.py", line 3096, in subscribe
web_1 | ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels))
web_1 | File "/usr/lib/python3.6/site-packages/redis/client.py", line 3003, in execute_command
web_1 | self.shard_hint
web_1 | File "/usr/lib/python3.6/site-packages/redis/connection.py", line 994, in get_connection
web_1 | connection.connect()
web_1 | File "/usr/lib/python3.6/site-packages/redis/connection.py", line 497, in connect
web_1 | raise ConnectionError(self._error_message(e))
web_1 | redis.exceptions.ConnectionError: Error 99 connecting to localhost:6379. Address not available.
web_1 |
web_1 | During handling of the above exception, another exception occurred:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
web_1 | return self.wsgi_app(environ, start_response)
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
web_1 | response = self.handle_exception(e)
web_1 | File "/usr/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
web_1 | return cors_after_request(app.make_response(f(*args, **kwargs)))
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
web_1 | reraise(exc_type, exc_value, tb)
web_1 | File "/usr/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
web_1 | raise value
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
web_1 | response = self.full_dispatch_request()
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
web_1 | rv = self.handle_user_exception(e)
web_1 | File "/usr/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
web_1 | return cors_after_request(app.make_response(f(*args, **kwargs)))
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
REDIS LOG
Redis, however, seems to be working:
redis_1 | 1:C 29 Mar 2019 02:33:32.722 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1 | 1:C 29 Mar 2019 02:33:32.722 # Redis version=5.0.3, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1 | 1:C 29 Mar 2019 02:33:32.722 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1 | 1:M 29 Mar 2019 02:33:32.724 * Running mode=standalone, port=6379.
redis_1 | 1:M 29 Mar 2019 02:33:32.724 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1 | 1:M 29 Mar 2019 02:33:32.724 # Server initialized
redis_1 | 1:M 29 Mar 2019 02:33:32.724 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
redis_1 | 1:M 29 Mar 2019 02:33:32.725 * DB loaded from disk: 0.000 seconds
redis_1 | 1:M 29 Mar 2019 02:33:32.725 * Ready to accept connections
config.py
class DevelopmentConfig(BaseConfig):
"""Development configuration"""
DEBUG_TB_ENABLED = True
DEBUG = True
BCRYPT_LOG_ROUNDS = 4
#set key
#sqlalchemy
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
#SQLALCHEMY_DATABASE_URI= "sqlite:///models/data/database.db"
# mail
MAIL_SERVER='smtp.gmail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_DEBUG = True
MAIL_USERNAME = 'me#gmail.com'
MAIL_PASSWORD = 'MEfAc6w74WGx'
SEVER_NAME = 'http://127.0.0.1:8080'
# celery broker
REDIS_HOST = "0.0.0.0"
REDIS_PORT = 6379
BROKER_URL = os.environ.get('REDIS_URL', "redis://{host}:{port}/0".format(
host=REDIS_HOST,
port=str(REDIS_PORT)))
INSTALLED_APPS = ['routes']
# celery config
CELERYD_CONCURRENCY = 10
CELERY_BROKER_URL = BROKER_URL
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_IMPORTS = ('project.api.routes.background',)
what am I missing here?
TL;DR change redis://localhost:6379/0 to redis://redis:6379/0
When you run docker-compose, it creates a new network under which all your containers are running. Docker engine also creates an internal routing which allows all the containers to reference each other using their names.
In your case, your web and celery containers were trying to access redis over localhost. But inside the container, localhost means their own localhost. You need to change the configuration to point the hostname to the name of the container.
If you were not using docker, but had different machines for each of your container, localhost would have meant their own server. In order to connect to redis server, you would have passed the IP address of the machine on which redis was running. In docker, instead of IP address, you can just pass the name of the container because of the engine's routing discussed above.
Note that you can still assign static IP addresses to each of your container, and use those IP addresses instead of container_names. For more details, read the networking section of docker documents.

Python application cannot connect to PostgreSQL Docker

Can anyone help me on this?
Dockerfile for my image:
FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /hlcup
WORKDIR /hlcup
ADD requirements.txt /hlcup/
RUN pip install --upgrade pip
RUN pip3 install -r requirements.txt
ADD . /hlcup/
EXPOSE 80
EXPOSE 5432
My docker-compose.yml:
version: '3'
services:
db:
image: postgres
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
ports:
- "5432:5432"
web:
build: .
command: python3 main.py
volumes:
- .:/hlcup
- ./data:/tmp/data/
ports:
- "80:80"
depends_on:
- db
I run my build: docker-compose up --build
As a result, the application should connect to the database, but I get a connection error:
web_1 | conn = await asyncpg.connect(**DB_PARAMS)
web_1 | File "/usr/local/lib/python3.6/site-packages/asyncpg/connection.py", line 1688, in connect
web_1 | max_cacheable_statement_size=max_cacheable_statement_size)
web_1 | File "/usr/local/lib/python3.6/site-packages/asyncpg/connect_utils.py", line 551, in _connect
web_1 | raise last_error
web_1 | File "/usr/local/lib/python3.6/site-packages/asyncpg/connect_utils.py", line 543, in _connect
web_1 | connection_class=connection_class)
web_1 | File "/usr/local/lib/python3.6/site-packages/asyncpg/connect_utils.py", line 513, in _connect_addr
web_1 | connector, timeout=timeout, loop=loop)
web_1 | File "/usr/local/lib/python3.6/asyncio/tasks.py", line 352, in wait_for
web_1 | return fut.result()
web_1 | File "/usr/local/lib/python3.6/asyncio/base_events.py", line 776, in create_connection
web_1 | raise exceptions[0]
web_1 | File "/usr/local/lib/python3.6/asyncio/base_events.py", line 763, in create_connection
web_1 | yield from self.sock_connect(sock, address)
web_1 | File "/usr/local/lib/python3.6/asyncio/selector_events.py", line 451, in sock_connect
web_1 | return (yield from fut)
web_1 | File "/usr/local/lib/python3.6/asyncio/selector_events.py", line 481, in _sock_connect_cb
web_1 | raise OSError(err, 'Connect call failed %s' % (address,))
web_1 | ConnectionRefusedError: [Errno 111] Connect call failed ('0.0.0.0', 5432)
You container web is tries to connecting to database with local ip 0.0.0.0:5432 and the database is on other container with another ip.
docker-compose support DNS between container, so I would try change in the python app from an ip number to a DNS.
In your docker-compose file, the postgres database DNS is db

How to properly run database (rethinkdb) with docker-compose?

I need help to run a database with docker and nodejs. I do not understand where I'm going wrong, but I can not make connection between my container with database and my container with node. This is the db link in docker: "https://hub.docker.com/_/rethinkdb/".Then follows:
my Dockerfile
FROM node:latest
ENV HOME=/src/jv-agricultor
RUN mkdir -p $HOME/
WORKDIR $HOME/
ADD package* $HOME/
RUN npm install
EXPOSE 80
ADD . $HOME/
CMD ["node", "node_modules/.bin/nodemon", "-L", "bin/www"]
My docker-compose.yml
version: "3"
volumes:
rethindb-data:
external: true
services:
db:
image: rethinkdb:latest
ports:
- "8080:8080"
- "29015:29015"
- "28015:28015"
api:
image: hello-nodemon
environment:
- NODE_ENV=development
- PORT=80
- DB_HOST=localhost
- DB_PORT=28015
deploy:
# replicas: 5
resources:
limits:
cpus: "0.1"
memory: 50M
restart_policy:
condition: on-failure
ports:
- "3000:80"
volumes:
- .:/src/jv-agricultor
- /src/jv-agricultor/node_modules
depends_on:
- db
networks:
- webnet
networks:
webnet:
i run: docker stack deploy -c docker-compose.yml webservice
My docker service
ID NAME MODE REPLICAS IMAGE PORTS
yez42a7w8khs webservice_api replicated 1/1 hello-nodemon:latest *:3000->80/tcp
n8idu78cp18m webservice_db replicated 1/1 rethinkdb:latest *:8080->8080/tcp,*:28015->28015/tcp,*:29015->29015/tcp
My docker service api (here is node/express)
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
p20qdagcspjc webservice_api.1 hello-nodemon:latest abner Running Running 28 minutes ago
My Docker service db
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
3046xuo4l8ix webservice_db.1 rethinkdb:latest abner Running Running 30 minutes ago
My logs internal db
webservice_db.1.3046xuo4l8ix#abner | Recursively removing directory /data/rethinkdb_data/tmp
webservice_db.1.3046xuo4l8ix#abner | Initializing directory /data/rethinkdb_data
webservice_db.1.3046xuo4l8ix#abner | Running rethinkdb 2.3.6~0jessie (GCC 4.9.2)...
webservice_db.1.3046xuo4l8ix#abner | Running on Linux 4.15.0-24-generic x86_64
webservice_db.1.3046xuo4l8ix#abner | Loading data from directory /data/rethinkdb_data
webservice_db.1.3046xuo4l8ix#abner | Listening for intracluster connections on port 29015
webservice_db.1.3046xuo4l8ix#abner | Listening for client driver connections on port 28015
webservice_db.1.3046xuo4l8ix#abner | Listening for administrative HTTP connections on port 8080
webservice_db.1.3046xuo4l8ix#abner | Listening on cluster addresses: 127.0.0.1, 172.18.0.3, 10.0.5.182, 10.0.5.183, 10.255.11.212, 10.255.11.213
webservice_db.1.3046xuo4l8ix#abner | Listening on driver addresses: 127.0.0.1, 172.18.0.3, 10.0.5.182, 10.0.5.183, 10.255.11.212, 10.255.11.213
webservice_db.1.3046xuo4l8ix#abner | Listening on http addresses: 127.0.0.1, 172.18.0.3, 10.0.5.182, 10.0.5.183, 10.255.11.212, 10.255.11.213
webservice_db.1.3046xuo4l8ix#abner | Server ready, "069fd360acfb_jot" c1cf5173-cf0d-457f-9c8f-4ba1756c28d8
my app.js
...
var connect = require('./lib/connect');
console.log('DB_HOST: ' + process.env.DB_HOST);
console.log('DB_PORT: ' + process.env.DB_PORT);
console.log('PORT: ' + process.env.PORT);
console.log('NODE_ENV: ' + process.env.NODE_ENV);
...
My connect middleware
'use strict'
// import r from 'rethinkdb';
var r = require('rethinkdb');
module.exports._connect = (function _connect(req, res, next) {
r.connect( {host: process.env.DB_HOST, port: process.env.DB_PORT}, (err, conn) => {
console.log(err);
})
})();
My service docker api logs respose
webservice_api.1.p20qdagcspjc#abner | [nodemon] restarting due to changes...
webservice_api.1.p20qdagcspjc#abner | [nodemon] starting `node bin/www`
webservice_api.1.p20qdagcspjc#abner | DB_HOST: localhost
webservice_api.1.p20qdagcspjc#abner | DB_PORT: 28015
webservice_api.1.p20qdagcspjc#abner | PORT: 80
webservice_api.1.p20qdagcspjc#abner | NODE_ENV: development
webservice_api.1.p20qdagcspjc#abner | { ReqlDriverError: Could not connect to localhost:28015.
webservice_api.1.p20qdagcspjc#abner | connect ECONNREFUSED 127.0.0.1:28015
webservice_api.1.p20qdagcspjc#abner | at ReqlDriverError.ReqlError [as constructor] (/src/jv-agricultor/node_modules/rethinkdb/errors.js:23:13)
webservice_api.1.p20qdagcspjc#abner | at new ReqlDriverError (/src/jv-agricultor/node_modules/rethinkdb/errors.js:68:50)
webservice_api.1.p20qdagcspjc#abner | at TcpConnection.<anonymous> (/src/jv-agricultor/node_modules/rethinkdb/net.js:94:27)
webservice_api.1.p20qdagcspjc#abner | at Object.onceWrapper (events.js:273:13)
webservice_api.1.p20qdagcspjc#abner | at TcpConnection.emit (events.js:182:13)
webservice_api.1.p20qdagcspjc#abner | at Socket.<anonymous> (/src/jv-agricultor/node_modules/rethinkdb/net.js:705:22)
webservice_api.1.p20qdagcspjc#abner | at Socket.emit (events.js:187:15)
webservice_api.1.p20qdagcspjc#abner | at emitErrorNT (internal/streams/destroy.js:82:8)
webservice_api.1.p20qdagcspjc#abner | at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
webservice_api.1.p20qdagcspjc#abner | at process._tickCallback (internal/process/next_tick.js:63:19)
webservice_api.1.p20qdagcspjc#abner | From previous event:
webservice_api.1.p20qdagcspjc#abner | at Function.<anonymous> (/src/jv-agricultor/node_modules/rethinkdb/net.js:945:10)
webservice_api.1.p20qdagcspjc#abner | at Function.connect (/src/jv-agricultor/node_modules/rethinkdb/util.js:43:16)
webservice_api.1.p20qdagcspjc#abner | at _connect (/src/jv-agricultor/lib/connect.js:9:7)
webservice_api.1.p20qdagcspjc#abner | at Object.<anonymous> (/src/jv-agricultor/lib/connect.js:19:3)
webservice_api.1.p20qdagcspjc#abner | at Module._compile (internal/modules/cjs/loader.js:689:30)
webservice_api.1.p20qdagcspjc#abner | at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
webservice_api.1.p20qdagcspjc#abner | at Module.load (internal/modules/cjs/loader.js:599:32)
webservice_api.1.p20qdagcspjc#abner | at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
webservice_api.1.p20qdagcspjc#abner | at Function.Module._load (internal/modules/cjs/loader.js:530:3)
webservice_api.1.p20qdagcspjc#abner | at Module.require (internal/modules/cjs/loader.js:637:17)
webservice_api.1.p20qdagcspjc#abner | at require (internal/modules/cjs/helpers.js:20:18)
webservice_api.1.p20qdagcspjc#abner | at Object.<anonymous> (/src/jv-agricultor/app.js:14:15)
webservice_api.1.p20qdagcspjc#abner | at Module._compile (internal/modules/cjs/loader.js:689:30)
webservice_api.1.p20qdagcspjc#abner | at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
webservice_api.1.p20qdagcspjc#abner | at Module.load (internal/modules/cjs/loader.js:599:32)
webservice_api.1.p20qdagcspjc#abner | at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
webservice_api.1.p20qdagcspjc#abner | at Function.Module._load (internal/modules/cjs/loader.js:530:3)
webservice_api.1.p20qdagcspjc#abner | at Module.require (internal/modules/cjs/loader.js:637:17)
webservice_api.1.p20qdagcspjc#abner | at require (internal/modules/cjs/helpers.js:20:18)
webservice_api.1.p20qdagcspjc#abner | name: 'ReqlDriverError',
webservice_api.1.p20qdagcspjc#abner | msg:
webservice_api.1.p20qdagcspjc#abner | 'Could not connect to localhost:28015.\nconnect ECONNREFUSED 127.0.0.1:28015',
webservice_api.1.p20qdagcspjc#abner | frames: undefined,
webservice_api.1.p20qdagcspjc#abner | message:
webservice_api.1.p20qdagcspjc#abner | 'Could not connect to localhost:28015.\nconnect ECONNREFUSED 127.0.0.1:28015' }
docker-compose does inter-service communication by service name, so the value of DB_HOST should be db.
On a side note, unless you need to expose the database outside of the stack, you do not need the port mapping.
#Alex Karshin It is unnecessary to fully specify the container name. The first example in the docker-compose networking docs shows how simple it really is.
spawnia has a point, but might not have the right answer. If you take a look at docker ps -a the name of your database container is webservice_db. Therefore, you will not be successful if you try to connect to rethinkdb on localhost (cuz obviously it's not on localhost).
You must either hardcode the container name (webservice_db) to your config file, or do set it in docker-compose.yml. But if you do, I suggest you set the container names explicitly:
version: "3"
...
services:
db:
container_name: webservice_db
...
api:
container_name: webservice_api
environment:
- NODE_ENV=development
- PORT=80
- DB_HOST= webservice_db
- DB_PORT=28015
...
There, now it should work normally.

Resources