Docker-compose - Redis at 0.0.0.0 instead of 127.0.0.1 - ruby-on-rails

I havs migrated my Rails app (local dev machine) to Docker-Compose. All is working except the Worker Rails instance (batch) cannot connect to Redis.
Completed 500 Internal Server Error in 40ms (ActiveRecord: 2.3ms)
Redis::CannotConnectError (Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)):
In my docker-compose.yml
redis:
image: redis
ports:
- "6379:6379"
batch:
build: .
command: bundle exec rake environment resque:work QUEUE=*
volumes:
- .:/app
links:
- db
- redis
environment:
- REDIS_URL=redis://redis:6379
I think the Redis instance is available via the IP of the Docker host.
$ docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS
default * virtualbox Running tcp://192.168.99.100:2376 v1.10.0
Accessing via 0.0.0.0 doesn't work
$ curl 0.0.0.0:6379
curl: (7) Failed to connect to 0.0.0.0 port 6379: Connection refused
Accessing via the docker-machine IP I think works:
$ curl http://192.168.99.100:6379
-ERR wrong number of arguments for 'get' command
-ERR unknown command 'Host:'
EDIT
After installing redis-cli in the batch instance, I was able to hit the redis server using the 'redis' hostname. I think the problem is possibly in the Rails configuration itself.

Facepalm!!!
The docker containers were communicating just fine, the problem was I hadn't told Resque (the app using Redis) where to find it. Thank you to "The Real Bill" for pointing out I should be using docker-cli.
For anyone else using Docker and Resque, you need this in your config/initializers/resque.rb file:
Resque.redis = Redis.new(host: 'redis', port: 6379)
Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection }

If you run
docker-compose run --rm batch env | grep REDIS
you will get the env variables that your container has (the link line in the compose will auto-generate some).
Then all you need to do is look for one along the lines of _REDIS_1_PORT... and use the correct one. I have never had luck connecting my rails to another service in any other way. But luckily these env variables are always generated on start so they will be up to date even if the container IP happens to change between startups.

You should use the hostname redis to connect to the service, although you may need to wait for redis to start.

Related

Request between Docker containers failing dial tcp 172.18.0.6:3050: connect: connection refused

I am struggling with Go requests between containers.
The issue that I have that the rest of my containers can send request to the node Container that give response, but when I send request from my GoLang application to node I get that refuse error "dial tcp 172.18.0.6:3050: connect: connection refused".
So my whole docker set up is:
version: "3.3"
services:
##########################
### SETUP SERVER CONTAINER
##########################
node:
# Tell docker what file to build the server from
image: myUserName/mernjs:node-dev
build:
context: ./nodeMyApp
dockerfile: Dockerfile.dev
# The ports to expose
expose:
- 3050
# Port mapping
ports:
- 3050:3050
# Volumes to mount
volumes:
- ./nodeMyApp/src:/app/server/src
# Run command
# Nodemon for hot reloading (-L flag required for polling in Docker)
command: nodemon -L src/app.js
# Connect to other containers
links:
- mongo
# Restart action
restart: always
react:
ports:
- 8000:8000
build:
context: ../reactMyApp
dockerfile: Dockerfile.dev
volumes:
- ../reactMyApp:/usr/src/app
- /usr/src/app/node_modules
- /usr/src/app/.next
restart: always
environment:
- NODE_ENV=development
golang:
build:
context: ../goMyApp
environment:
- MONGO_URI=mongodb://mongo:27017
# Volumes to mount
volumes:
- ../goMyApp:/app/server
links:
- mongo
- node
restart: always
So my React app can send the request to "http://node:3050/api/greeting/name" and it get the response even that react app is not linked to the node app but when Golang app sends request to node docker container it gets connection refuse message GetJson err: Get "http://node:3050/api/greeting/name": dial tcp 172.18.0.6:3050: connect: connection refused
func GetJson(url string, target interface{}) error {
r, err := myClient.Get(url)
if err != nil {
fmt.Println("GetJson err: ", err)
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
type ResultsDetails struct {
Greeting string `bson:"greatingMessage" json:"greatingMessage"`
Message string `bson:"message" json:"message"`
}
func GetGreetingDetails(name string) ResultsDetails {
var resp ResultsDetails
GetJson("http://node:3050/api/greeting/"+name, &resp)
return resp
}
So how do I solve the Golang request to another Docker Node Container when docker doesnt see the host as the name of my container 'node'?
Update:
By accident i put Golang port, which it doenst run on any port since it is application that checks on database records. So it hasnt got any api, therefore it is not running on any port.
Is that could be the problem why my golang application cannot communication to other containers?
Since i have also another golang application which is api application and it is running on 5000 port and it is well communicating to my node application?
Network info:
After checking the network if node and golang share the same network and the answer is yes. All containers share the same network
(Unrelated to my issue) To anyone who has "dial tcp connection refused" issue I suggest to go though that guide https://maximorlov.com/4-reasons-why-your-docker-containers-cant-talk-to-each-other/. Really helpful. To those who this guide wont help prob read bellow this, maybe you trying to request the container api after just containers were built :D
For those who was interested what was wrong:
Technically reason why I was getting this error is because of the request that I was trying to run, was just when all containers were built.
I believe there is some delay to the network after containers are built. Thats why there host was throwing "dial tcp 172.18.0.6:3050: connect: connection refused" I've run that test on other containers that could possibly send request to that node container and they were all failing after the build time. But when re-requesting after few seconds all worked out.
Sorry to bother you guys. I really spent 3 days into this issue. And I was looking into completely wrong direction. Never thought that the issue is that silly :D
Thanks for you time.
I've met the same error in my harbor registry service.
After I docker exec -it into the container, and check if the service is available, and finally I found that http_proxy has been set.
Remove the http_proxy settings for docker service, then it works like a charm.
Failed on load rest config err:Get "http://core:8080/api/internal/configurations": dial tcp 172.22.0.8:8080: connect: connection refused
$docker exec -it harbor-jobservice /bin/bash
$echo $http_proxy $https_proxy

Spring Boot tries to connect to Mongo localhost

I have a Spring Boot 2.x project using Mongo. I am running this via Docker (using compose locally) and Kubernetes. I am trying to connect my service to a Mongo server. This is confusing to me, but for development I am using a local instance of Mongo, but deployed in GCP I have named mongo services.
here is my application.properties file:
#mongodb
spring.data.mongodb.uri= mongodb://mongo-serviceone:27017/serviceone
#logging
logging.level.org.springframework.data=trace
logging.level.=trace
And my Docker-compose:
version: '3'
# Define the services/containers to be run
services:
service: #name of your service
build: ./ # specify the directory of the Dockerfile
ports:
- "3009:3009" #specify ports forwarding
links:
- mongo-serviceone # link this service to the database service
volumes:
- .:/usr/src/app
depends_on:
- mongo-serviceone
mongo-serviceone: # name of the service
image: mongo
volumes:
- ./data:/data/db
ports:
- "27017:27017"
When I try docker-compose up . I get the following error:
mongo-serviceone_1 | 2018-08-22T13:50:33.454+0000 I NETWORK
[initandlisten] waiting for connections on port 27017 service_1
| 2018-08-22 13:50:33.526 INFO 1 --- [localhost:27017]
org.mongodb.driver.cluster : Exception in monitor thread
while connecting to server localhost:27017 service_1
| service_1 | com.mongodb.MongoSocketOpenException:
Exception opening socket service_1 | at
com.mongodb.connection.SocketStream.open(SocketStream.java:62)
~[mongodb-driver-core-3.6.3.jar!/:na]
running docker ps shows me:
692ebb72cf30 serviceone_service "java -Djava.securit…" About an hour ago Up 9 minutes 0.0.0.0:3009->3009/tcp, 8080/tcp serviceone_service_1
6cd55ae7bb77 mongo "docker-entrypoint.s…" About an hour ago Up 9 minutes 0.0.0.0:27017->27017/tcp serviceone_mongo-serviceone_1
While I am trying to connect to a local mongo, I thought that by using the name "mongo-serviceone"
Hard to tell what the exact issue is, but maybe this is just an issue because of the space " " after "spring.data.mongodb.uri=" and before "mongodb://mongo-serviceone:27017/serviceone"?
If not, maybe exec into the "service" container and try to ping the mongodb with: ping mongo-serviceone:27017
Let me know the output of this, so I can help you analyze and fix this issue.
Alternatively, you could switch from using docker compose to a Kubernetes native dev tool, as you are planning to run your application on Kubernetes anyways. Here is a list of possible tools:
Allow hot reloading:
DevSpace: https://github.com/covexo/devspace
ksync: https://github.com/vapor-ware/ksync
Pure CI/CD tools for dev:
Skaffold: https://github.com/GoogleContainerTools/skaffold
Draft: https://github.com/Azure/draft
For most of them, you will only need minikube or a dev namespace inside your existing cluster on GCP.
Looks like another application was running on port 27017 on your localhost Similar reported issue
quick way to check on linux/mac:
telnet 127.0.01 27017
check logs files:
docker logs serviceone_service

Prisma Deploy Docker error "Could not connect to server"

This is steps I have done
prisma init
I set postgresql for database in my local(not exist).
It created 3 files, datamodel.graphql, docker-compose.yml, prisma.yml
docker-compose up -d
I confirmed it running successfully
But if I call prisma deploy, it shows me error
Could not connect to server at http://localhost:4466. Please check if your server is running.
All I have done is standard operation described in manual and there is no customization in
https://www.prisma.io/docs/tutorials/deploy-prisma-servers/local-(docker)-meemaesh3k
And this is docker-compose.yml
version: '3'
services:
prisma:
image: prismagraphql/prisma:1.11
restart: always
ports:
- "4466:4466"
environment:
PRISMA_CONFIG: |
port: 4466
# uncomment the next line and provide the env var PRISMA_MANAGEMENT_API_SECRET=my-secret to activate cluster security
# managementApiSecret: my-secret
databases:
default:
connector: postgres
host: localhost
port: '5432'
database: databasename
schema: public
user: postgres
password: root
migrations: true
What am I missing?
I found this solution to the same problem i was facing
docker-machine ip default
Use this address and replace the "localhost" with the IP with the above command to look something like this in prisma.yml file
endpoint: http://1xx.1xx.xx.xxx:4466
The answer is referred from this Github Link
The documentation mentions:
docker ps
You should see output similar to this:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2b799c529e73 prismagraphql/prisma:1.7 "/bin/sh -c /app/sta…" 17 hours ago Up 7 hours 0.0.0.0:4466->4466/tcp myapp_prisma_1
757dfba212f7 mysql:5.7 "docker-entrypoint.s…" 17 hours ago
(Here shown with mysql, but valid with postgresql too)
The point is: there should be two containers running, not one.
Check docker-compose logs to see why the second one (database) did not start.
instead of docker-compose up -d
USE:
docker-compose up
and keep the window running which will keep localhost:4466 alive.
Note : If u want to connect to connect to the database created in docker, you need to map the port in the following way:
docker run --name <ENTER_NAME> -e POSTGRES_PASSWORD=<ENTER_PASSWORD> -d -p 5433:5432 postgres
In the above case PORT(5433) = HOST_PORT and PORT(5432) = CONTAINER_PORT

Remote debug docker+wildfly with intelliJ 2017.2.6

So there are a lot of posts around this subject, but none of which seems to help.
I have an application running on a wildfly server inside a docker container.
And for some reason I cannot connect my remote debugger to it.
So, it is a wildfly 11 server that has been started with this command:
/opt/jboss/wildfly/bin/standalone.sh -b 0.0.0.0 -bmanagement 0.0.0.0 -c standalone.xml --debug 9999;
And in my standalone.xml I have this:
<socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
The console output seems promising:
Listening for transport dt_socket at address: 9999
I can even access the admin console with the credentials admin:admin on localhost:9990/console
However IntelliJ refuses to connect... I've creates a remote JBoss Server configuration that in the server tab points to localhost with management port 9990.
And in the startup/connection tab I've entered 9999 as remote socket port.
The docker image has exposed the ports 9999 and 9990, and the docker-compose file binds those ports as is.
Even with all of this IntelliJ throws this message when trying to connect:
Error running 'remote':
Unable to open debugger port (localhost:9999): java.io.IOException "handshake failed - connection prematurally closed"
followed by
Error running 'remote':
Unable to connect to the localhost:9990, reason:
com.intellij.javaee.process.common.WrappedException: java.io.IOException: java.net.ConnectException: WFLYPRT0053: Could not connect to remote+http://localhost:9990. The connection failed
I'm completely lost as to what the issue might be...
Interessting addition is that after intelliJ fails, if I invalidate caches and restart then wildfly reprints the message saying that it is listening on port 9999
In case someone else in the future comes to this thread with he same issue, I found this solution here:
https://github.com/jboss-dockerfiles/wildfly/issues/91#issuecomment-450192272
Basically, apparart from the --debug parameter, you also need to pass *:8787
Dockerfile:
CMD ["/opt/jboss/wildfly/bin/standalone.sh", "-b", "0.0.0.0", "-bmanagement", "0.0.0.0", "--debug", "*:8787"]
docker-compose:
ports:
- "8080:8080"
- "8787:8787"
- "9990:9990"
command: /opt/jboss/wildfly/bin/standalone.sh -b 0.0.0.0 -bmanagement 0.0.0.0 --debug *:8787
I have not tested the docker-compose solution, as my solution was on dockerfile.
Not sure if this can be seen as an answer since it goes around the problem.
But the way I solved this, was by adding a "pure" remote configuration in intelliJ instead of jboss remote. This means that it won't automagically deploy, but I'm fine with that

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

Before anything, please note that I have found several similar questions on Stack Overflow and articles all over the web, but none of those helped me fix my issue:
PG Error could not connect to server: Connection refused Is the server running on port 5432?
PG::ConnectionBad - could not connect to server: Connection refused
psql: could not connect to server: Connection refused
Now, here is the issue:
I have a Rails app that works like a charm.
With my collaborator, we use GitHub to work together.
We have a master and an mvp branches.
I recently updated my git version with Homebrew (Mac).
We use Foreman to start our app locally.
Now, when I try to launch the app locally, I get the following error:
PG::ConnectionBad at /
could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
I tried to reboot my computers several times.
I also checked the content of /usr/local/var/postgres:
PG_VERSION pg_dynshmem pg_multixact pg_snapshots pg_tblspc postgresql.conf
base pg_hba.conf pg_notify pg_stat pg_twophase postmaster.opts
global pg_ident.conf pg_replslot pg_stat_tmp pg_xlog server.log
pg_clog pg_logical pg_serial pg_subtrans postgresql.auto.conf
As you can see, there is no postmaster.pid file in there.
Any idea how I could fix this?
run postgres -D /usr/local/var/postgres and you should see something like:
FATAL: lock file "postmaster.pid" already exists
HINT: Is another postmaster (PID 379) running in data directory "/usr/local/var/postgres"?
Then run kill -9 PID in HINT
And you should be good to go.
You most likely ran out of battery and your postgresql server didn't shutdown correctly.
The easiest workaround is to download the official postgresql app and launch it: it will force the server to start (http://postgresapp.com/)
Most likely it's because your system shutdown unexpectedly
Try
postgres -D /usr/local/var/postgres
You might see
FATAL: lock file "postmaster.pid" already exists
HINT: Is another postmaster (PID 449) running in data directory "/usr/local/var/postgres"?
Then try
kill -9 PID
example
kill -9 419
And it should start postgres normally
The postgresql server might be down and the solution might be as simple as running:
sudo service postgresql start
which fixed the issue for me.
This could be caused by the pid file created for postgres which has not been deleted due to unexpected shutdown. To fix this, remove this pid file.
Find the postgres data directory. On a MAC using homebrew it is /usr/local/var/postgres/, other systems it might be /usr/var/postgres/
Remove pid file by running:
rm postmaster.pid
Restart postgress. On Mac, run:
brew services restart postgresql
I had almost just as same error with my Ruby on Rails application running postgresql(mac). This worked for me:
brew services restart postgresql
This worked in my case:
brew uninstall postgresql
rm -fr /usr/local/var/postgres/
brew install postgresql
In my case PostgreSQL updates from version 13.4 to 14 in background, so it fixes by:
brew postgresql-upgrade-database
In other case the problem fixed by:
rm -rf /usr/local/var/postgres/postmaster.pid
or
rm -rf /opt/homebrew/var/postgres/postmaster.pid
Restart service postgresql:
brew services restart postgresql
PS:
How can you understand what is the problem?
For first see what service is not correct started:
brew services list
For second show file postgres.log, where will be the error:
tail -f /usr/local/var/log/postgres.log
or
tail -f /opt/homebrew/var/log/postgres*
And so find answer by this error's text
I resolved the issue via this command
pg_ctl -D /usr/local/var/postgres start
At times, you might get this error
pg_ctl: another server might be running; trying to start server anyway
So, try running the following command and then run the first command given above.
pg_ctl -D /usr/local/var/postgres stop
Step 1:
cd /etc/postgresql/12/main/
open file named postgresql.conf
sudo nano postgresql.conf
add this line to that file
listen_addresses = '*'
then open file named pg_hba.conf
sudo nano pg_hba.conf
and add this line to that file
host all all 0.0.0.0/0 md5
It allows access to all databases for all users with an encrypted password
restart your server
sudo /etc/init.d/postgresql restart
This is how I solved my problem:
see the status of services
brew services list
and the output was :
Name Status User Plist
postgresql error myuser /Users/myuser/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
unbound stopped
I change the file name in this path, you can also remove it
mv /Users/myuser/Library/LaunchAgents/homebrew.mxcl.postgresql.plist /Users/myuser/Library/LaunchAgents/homebrew.mxcl.postgresql.plist_temp
and then reboot the os
sudo reboot
after booting I started the postgresql and it worked.
brew services start postgresql
Find postgresql#10 service directory
$ ls /usr/local/var/postgresql#10
Find file postmaster.pid and delete that file
$ rm -f postmaster.pid
Restart postgres service using
$ brew services restart postgresql#10
This worked for me:
run
sudo lsof -i :<port_number>
after that it will display the PID which is currently attached to the process.
After that run sudo kill -9 <PID>
if that doesn't work,
try the solution offered by user8376606 it would definitely work!
If you want to restart Postgresql on Linux, then you have to use the following command.
/etc/init.d/postgresql restart
In my case
I have changed the port in postgresql.conf file
and restart postgresql services in
Run => service.msc => Restart
now retry
First I tried
lsof -wni tcp:5432
but it doesn't show any PID number.
Second I tried
Postgres -D /usr/local/var/postgres
and it showed that server is listening.
So I just restarted my mac to restore all ports back and it worked for me.
For Docker users: In my case it was caused by excessive docker image size. You can remove unused data using prune command:
docker system prune --all --force --volumes
Warning: as per manual (docker system prune --help):
This will remove:
all stopped containers
all networks not used by at least one container
all dangling images
all dangling build cache
I encountered a similar problem when I was trying to connect my Django application to PostgreSQL database.
I wrote my Dockerfile with instructions to setup the Django project followed by instructions to install PostgreSQL and run Django server in my docker-compose.yml.
I defined two services in my docker-compose-yml.
services:
postgres:
image: "postgres:latest"
environment:
- POSTGRES_DB=abc
- POSTGRES_USER=abc
- POSTGRES_PASSWORD=abc
volumes:
- pg_data:/var/lib/postgresql/data/
django:
build: .
command: python /code/manage.py runserver 0.0.0.0:8004
volumes:
- .:/app
ports:
- 8004:8004
depends_on:
- postgres
Unfortunately whenever I used to run docker-compose up then same err. used to pop up.
And this is how my database was defined in Django settings.py.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'abc',
'USER': 'abc',
'PASSWORD': 'abc',
'HOST': '127.0.0.1',
'PORT': '5432',
'OPTIONS': {
'client_encoding': 'UTF8',
},
}
}
So, In the end I made use of docker-compose networking which means if I change the host of my database to postgres which is defined as a service in docker-compose.yml will do the wonders.
So, Replacing 'HOST': '127.0.0.1' => 'HOST': 'postgres' did wonders for me.
After replacement this is how your Database config in settings.py will look like.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'abc',
'USER': 'abc',
'PASSWORD': 'abc',
'HOST': 'postgres',
'PORT': '5432',
'OPTIONS': {
'client_encoding': 'UTF8',
},
}
}
I often encounter this problem on windows,the way I solved the problem is Service - Click PostgreSQL Database Server 8.3 - Click the second tab "log in" - choose the first line "the local system account".
It also gives the same error if you just stop your PostgreSQL app. You just need to start it again. (PostgreSQL 11)
I have faced the same issue and I was unable to start the postgresql server and was unable to access my db even after giving password, and I have been doing all the possible ways.
This solution worked for me,
For the Ubuntu users:
Through command line, type the following commands:
1.service --status-all (which gives list of all services and their status. where "+" refers to running and "-" refers that the service is no longer running)
check for postgresql status, if its "-" then type the following command
2.systemctl start postgresql (starts the server again)
refresh the postgresql page in browser, and it works
For the Windows users:
Search for services, where we can see list of services and the right click on postgresql, click on start and server works perfectly fine.
In my case I forgot to change the database from postgres (on my production) back to sqlite3 which I was using for development.
It's working for me >>Node.Js App
user#MacBook-Pro % sudo lsof -i :5430
Output
COMMAND PID user FD TYPE DEVICE SIZE/OFF NODE NAME
node 7885 user 21u IPv6 0x2e7d89f6118f95b9 0t0 TCP *:radec-corp (LISTEN)
Kill the PID
user#MacBook-Pro % sudo kill -9 7885
One more test
user#MacBook-Pro % sudo lsof -i :5430
user#MacBook-Pro % "No more running PID for the port 5430"
In my case, on a Ruby on Rails project, I removed a .pid file from the folder tmp/pids and restart the system.
Had the same issue. I checked that my database.yml file, (dev mode) host was pointing to 5433. I updated it to 5432 and it worked.
Just in case someone needs this for windows, read on.
On windows hit the Windows button + R
then enter services.msc and look for postgresql-x64-14, Right click it and click start
Then go back to your PgAdmin4 for windows and then enter your master password if asked.
From here, you should be able to proceed as usual with viewing of the db schemas.
Also, for Django, restart your server with CTR+C then python manage.py runserver (assuming you're working inside a virtual env)
Good luck
ps -ef|grep postgres
Then kill the process with PID
sudo kill -9 PID
Then start the postgresql
sudo service postgresql start
In my case I when it happens to me I need to do the following steps:
1º Step
Log in postgres user:
#sudo su postgres
2º Step
Run the following steps: /opt/PostgreSQL/10/bin/postgres -D /opt/PostgreSQL/10/data -r /usr/local/var/postgres/server.log
Explanation:
We access the utility of postgres located at /opt/PostgreSQL/10/bin/ in your case could be another but identify where it's.
After this step we tell to the utility of postgres where the it's data folder is by using the option -D, this data folder contains all necessary configuration of postgres server.
The option -r we tell to postgres where to send stdout and stderr to given file, in my case the file that I used is /usr/local/var/postgres/server.log
Note:
I'm using Postgre 10
Linux Ubuntu

Resources