Testcontainers-java: Connection refused to Postgres container

Created on 10 Apr 2018  ·  27Comments  ·  Source: testcontainers/testcontainers-java

I'm trying to use TestContainers with Postgres, using the sample Postgres test here gives me connection errors.

I have Docker for Mac installed, but TestContainers doesn't seem to be using that, instead it started a new docker-machine VM.

I'm also confused that the test passes successfully; given the connection errors shouldn't it be failing?

[2018-04-10 12:43:46.218] INFO   [main] o.t.d.DockerMachineClientProviderStrategy -  - Found docker-machine, and will use machine named default 
[2018-04-10 12:43:47.050] INFO   [main] o.t.d.DockerMachineClientProviderStrategy -  - Docker daemon IP address for docker machine default is 192.168.99.100 
[2018-04-10 12:43:48.441] INFO   [main] o.t.d.DockerClientProviderStrategy -  - Found Docker environment with docker-machine 
[2018-04-10 12:43:48.443] INFO   [main] o.t.DockerClientFactory -  - Docker host IP address is 192.168.99.100 
[2018-04-10 12:43:48.684] INFO   [main] o.t.DockerClientFactory -  - Connected to docker: 
  Server Version: 1.11.2
  API Version: 1.23
  Operating System: Boot2Docker 1.11.2 (TCL 7.1); HEAD : a6645c3 - Wed Jun  1 22:59:51 UTC 2016
  Total Memory: 3950 MB 
[2018-04-10 12:43:49.630] INFO   [main] o.t.DockerClientFactory -  - Ryuk started - will monitor and terminate Testcontainers containers on JVM exit 
        ℹ︎ Checking the system...
        ✔ Docker version should be at least 1.6.0
        ✔ Docker environment should have more than 2GB free disk space
        ✔ File should be mountable
[2018-04-10 12:43:50.202] INFO   [main] 🐳 [postgres:latest] -  - Creating container for image: postgres:latest 
[2018-04-10 12:43:50.325] INFO   [main] 🐳 [postgres:latest] -  - Starting container with ID: 024bc36f4f55be337ec8f40319f3551a7ff5342cf7753826995c8d9c07ab6975 
[2018-04-10 12:43:50.657] INFO   [main] 🐳 [postgres:latest] -  - Container postgres:latest is starting: 024bc36f4f55be337ec8f40319f3551a7ff5342cf7753826995c8d9c07ab6975 
[2018-04-10 12:43:52.650] INFO   [main] 🐳 [postgres:latest] -  - Container postgres:latest started 
[2018-04-10 12:43:52.656] INFO   [main] c.z.h.HikariDataSource -  - HikariPool-1 - Starting... 
[2018-04-10 12:43:52.766] INFO   [main] c.z.h.HikariDataSource -  - HikariPool-1 - Start completed. 
Apr 10, 2018 12:43:52 PM org.postgresql.core.v3.ConnectionFactoryImpl log
WARNING: ConnectException occurred while connecting to 192.168.99.100:32771
java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:69)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:158)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
    at com.zaxxer.hikari.pool.HikariPool.access$200(HikariPool.java:70)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:630)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:616)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Apr 10, 2018 12:43:52 PM org.postgresql.Driver connect
SEVERE: Connection error: 
org.postgresql.util.PSQLException: Connection to 192.168.99.100:32771 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:247)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
    at com.zaxxer.hikari.pool.HikariPool.access$200(HikariPool.java:70)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:630)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:616)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:69)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:158)
    ... 16 more

Apr 10, 2018 12:43:53 PM org.postgresql.core.v3.ConnectionFactoryImpl log
WARNING: ConnectException occurred while connecting to 192.168.99.100:32771
java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:69)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:158)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
    at com.zaxxer.hikari.pool.HikariPool.access$200(HikariPool.java:70)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:630)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:616)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Apr 10, 2018 12:43:53 PM org.postgresql.Driver connect
SEVERE: Connection error: 
org.postgresql.util.PSQLException: Connection to 192.168.99.100:32771 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:247)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
    at com.zaxxer.hikari.pool.HikariPool.access$200(HikariPool.java:70)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:630)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:616)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:69)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:158)
    ... 16 more
areshading cliendocker-for-mac cliendocker-machine omacOS resolutioanswered typbug

Most helpful comment

Hi @monowai,
the answer is actually quite simple.

The getters in Testcontainers assume you are running on the host, not inside the container. That means, all generated urls will contain the container host + mapped port. Of course, localhost inside the container means the container itself and that's why its failing.

In your case, you can have an even simpler setup, since you can leverage Docker network DNS.
Give your PostgreSQLContainer a name on the network (use withNetworkAlias("postgres") setter) and then you can use the following static url in your Spring service: postgres://postgres:5432

Edit:
Okay, @bsideup just beat me to it 😄

All 27 comments

Hi @yissachar!
Please try Testcontainers 1.7.0, it should prioritize Docker for Mac over Docker Machine

I am using 1.7.0

How is Docker for Mac discovered? Wondering if I have something misconfigured (although I haven't modified anything knowingly - running the latest Docker for Mac with all the defaults).

For what it's worth, docker command does use Docker for Mac, so it's just TestContainers that is failing to use it.

I wonder... @yissachar please could you check your ~/.testcontainers.properties file?

This file normally caches last known-good docker daemon configuration. Even though we changed the default to favour Docker for Mac, if this file is effectively saying to prefer docker-machine, that preference might win.

I can’t remember if this is the exact behaviour, but might be worth just trying deleting this file...

@rnorth starting with 1.7.0 we will ignore "Docker Machine" from ~/.testcontainers.properties
Also, the pre-flight checks passed (including the port mapping part), means it is something else.

~/.testcontainers.properties doesn't seem to exist for me anyway.

Hi

I had the same error with the 1.7.2 | 1.7.1 | 1.7.0 versions.

11:29:23.051 [main] INFO  o.t.d.DockerMachineClientProviderStrategy - Found docker-machine, and will use machine named 
11:29:23.084 [main] ERROR o.t.d.DockerClientProviderStrategy - Could not find a valid Docker environment. Please check configuration. Attempted configurations were:
11:29:23.084 [main] ERROR o.t.d.DockerClientProviderStrategy -     ProxiedUnixSocketClientProviderStrategy: failed with exception NoClassDefFoundError (org/rnorth/tcpunixsocketproxy/TcpToUnixSocketProxy). Root cause ClassNotFoundException (org.rnorth.tcpunixsocketproxy.TcpToUnixSocketProxy)
11:29:23.085 [main] ERROR o.t.d.DockerClientProviderStrategy -     DockerMachineClientProviderStrategy: failed with exception InvalidConfigurationException (Exception when executing docker-machine status )
11:29:23.085 [main] ERROR o.t.d.DockerClientProviderStrategy - As no valid configuration was found, execution cannot continue

And by downgrading to the 1.6.0, it's working:

11:36:17.223 [main] INFO  o.t.d.DockerClientProviderStrategy - Found Docker environment with local Unix socket (via TCP proxy)
11:36:17.234 [main] INFO  o.testcontainers.DockerClientFactory - Docker host IP address is localhost
11:36:17.343 [main] INFO  o.testcontainers.DockerClientFactory - Connected to docker: 
  Server Version: 18.03.1-ce
  API Version: 1.37
  Operating System: Docker for Mac
  Total Memory: 3443 MB
11:36:22.290 [main] INFO  o.testcontainers.DockerClientFactory - Ryuk started - will monitor and terminate Testcontainers containers on JVM exit
        ℹ︎ Checking the system...
        ✔ Docker version should be at least 1.6.0
        ✔ Docker environment should have more than 2GB free disk space
        ✔ File should be mountable
11:36:22.392 [main] INFO  🐳 [mongo:3.6.4] - Pulling docker image: mongo:3.6.4. Please be patient; this may take some time but only needs to be done once.

Any idea to fix this please?

Thanks

Seems 1.7.+ versions are broken. I have the same problem on mac.
1.6.0 works fine

1.7.3 should fix it, please try :)

Great! it worked very fine. Thanks.

@yissachar could you please try it, so that we can close the issue? :)

Hmm, it now corrects to Docker for Mac properly, but the connection problem still remains:

[2018-05-22 15:22:08.002] INFO   [main] o.t.d.DockerClientProviderStrategy -  - Found Docker environment with local Unix socket (via TCP proxy) 
[2018-05-22 15:22:08.011] INFO   [main] o.t.DockerClientFactory -  - Docker host IP address is localhost 
[2018-05-22 15:22:08.164] INFO   [main] o.t.DockerClientFactory -  - Connected to docker: 
  Server Version: 18.03.0-ce
  API Version: 1.37
  Operating System: Docker for Mac
  Total Memory: 1998 MB 
[2018-05-22 15:22:11.203] INFO   [main] o.t.DockerClientFactory -  - Ryuk started - will monitor and terminate Testcontainers containers on JVM exit 
        ℹ︎ Checking the system...
        ✔ Docker version should be at least 1.6.0
        ✔ Docker environment should have more than 2GB free disk space
        ✔ File should be mountable
[2018-05-22 15:22:11.342] INFO   [main] ?.6.8] -  - Pulling docker image: postgres:9.6.8. Please be patient; this may take some time but only needs to be done once. 
[2018-05-22 15:22:19.635] INFO   [main] ?.6.8] -  - Creating container for image: postgres:9.6.8 
[2018-05-22 15:22:19.754] INFO   [main] ?.6.8] -  - Starting container with ID: ae1f697c501c1eeddadeb6e3c712d53fc67d5f549657310fbf55a7d27d7d1adb 
[2018-05-22 15:22:20.130] INFO   [main] ?.6.8] -  - Container postgres:9.6.8 is starting: ae1f697c501c1eeddadeb6e3c712d53fc67d5f549657310fbf55a7d27d7d1adb 
[2018-05-22 15:22:24.184] INFO   [main] ?.6.8] -  - Container postgres:9.6.8 started 
[2018-05-22 15:22:24.189] INFO   [main] c.z.h.HikariDataSource -  - HikariPool-1 - Starting... 
[2018-05-22 15:22:24.268] INFO   [main] c.z.h.HikariDataSource -  - HikariPool-1 - Start completed. 
May 22, 2018 3:22:24 PM org.postgresql.core.v3.ConnectionFactoryImpl log
WARNING: IOException occurred while connecting to localhost:32769
java.io.EOFException
    at org.postgresql.core.PGStream.receiveChar(PGStream.java:295)
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:455)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:207)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
    at com.zaxxer.hikari.pool.HikariPool.access$200(HikariPool.java:70)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:630)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:616)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

May 22, 2018 3:22:24 PM org.postgresql.Driver connect
SEVERE: Connection error: 
org.postgresql.util.PSQLException: The connection attempt failed.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:259)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
    at com.zaxxer.hikari.pool.HikariPool.access$200(HikariPool.java:70)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:630)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:616)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.EOFException
    at org.postgresql.core.PGStream.receiveChar(PGStream.java:295)
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:455)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:207)
    ... 16 more

May 22, 2018 3:22:24 PM org.postgresql.core.v3.ConnectionFactoryImpl log
WARNING: ConnectException occurred while connecting to localhost:32769
java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:69)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:158)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
    at com.zaxxer.hikari.pool.HikariPool.access$200(HikariPool.java:70)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:630)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:616)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

May 22, 2018 3:22:24 PM org.postgresql.Driver connect
SEVERE: Connection error: 
org.postgresql.util.PSQLException: Connection to localhost:32769 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:247)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
    at com.zaxxer.hikari.pool.HikariPool.access$200(HikariPool.java:70)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:630)
    at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:616)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:69)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:158)
    ... 16 more

Have the same issue while running repository tests for my service:

        Caused by:
        org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
            at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:265)
            at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
            at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
            at org.postgresql.Driver.makeConnection(Driver.java:450)
            at org.postgresql.Driver.connect(Driver.java:252)
            at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:117)
            at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:123)
            at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:375)
            at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:204)
            at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:459)
            at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:533)
            at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:114)
            at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:97)
            at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
            at org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy$TransactionAwareInvocationHandler.invoke(TransactionAwareDataSourceProxy.java:225)
            at com.sun.proxy.$Proxy164.prepareStatement(Unknown Source)
            at org.jooq.impl.ProviderEnabledConnection.prepareStatement(ProviderEnabledConnection.java:109)
            at org.jooq.impl.SettingsEnabledConnection.prepareStatement(SettingsEnabledConnection.java:73)
            at org.jooq.impl.AbstractResultQuery.prepare(AbstractResultQuery.java:233)
            at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:319)
            ... 14 more

            Caused by:
            java.net.ConnectException: Connection refused (Connection refused)
                at java.net.PlainSocketImpl.socketConnect(Native Method)
                at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
                at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
                at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
                at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
                at java.net.Socket.connect(Socket.java:589)
                at org.postgresql.core.PGStream.<init>(PGStream.java:68)
                at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
                ... 33 more

Also I'm not able to access this container's postgres DB via db client

Ok, it seems to be that this library creates a postgres (in my case) container and wraps it using some api.

> docker ps
CONTAINER ID        IMAGE                     COMMAND                  CREATED             STATUS              PORTS                     NAMES
3e447b534543        postgres:9.6.8            "docker-entrypoint.s…"   2 hours ago         Up 2 hours          0.0.0.0:32769->5432/tcp   adoring_einstein
7674ffed40a8        bsideup/moby-ryuk:0.2.2   "/app"                   2 hours ago         Up 2 hours          0.0.0.0:32768->8080/tcp   testcontainers-ryuk-6bffc879-fd42-4cff-9187-e63d8a6ac14e

I was able to connect to the database using this jdbc link: jdbc:postgresql://localhost:32769/.
The port is always changing for the new container.

If you provide a default configuration for your datasource, e.g.:

datasource:
    url: jdbc:postgresql://${DATABASE_HOST:localhost}:5432/your_db_name
    username: postgres
    password: postgres
    type: com.zaxxer.hikari.HikariDataSource
    driverClassName: org.postgresql.Driver

then exception described by me above is thrown.

So, it's mandatory to use this kind of configuration:

  datasource:
    url: jdbc:tc:postgresql:9.6.4://localhost:5432/your_db_name
    driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
    username: postgres
    password: postgres

My suggestion is to make a connection creation more obvious, so that the port could be the same always. Potential risk is when several containers are desired. But the following up question is "why?"

Tried running a PostgreSQLContainer but it is throwing the below error:

`java.lang.IllegalStateException: Could not find a valid Docker environment. Please see logs and check configuration

at org.testcontainers.dockerclient.DockerClientProviderStrategy.lambda$getFirstValidStrategy$3(DockerClientProviderStrategy.java:155)
at java.util.Optional.orElseThrow(Optional.java:290)
at org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:147)
at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:100)
at org.testcontainers.containers.GenericContainer.<init>(GenericContainer.java:142)
at org.testcontainers.containers.JdbcDatabaseContainer.<init>(JdbcDatabaseContainer.java:37)
at org.testcontainers.containers.PostgreSQLContainer.<init>(PostgreSQLContainer.java:30)
at org.testcontainers.containers.PostgreSQLContainer.<init>(PostgreSQLContainer.java:26)
at com.snaplogic.snaps.postgres.SelectTest.testSimple(SelectTest.java:358)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)`

The error throws at the below line:
PostgreSQLContainer postgres = new PostgreSQLContainer();

Tried using the below dependency:
<dependency> <groupId>org.testcontainers</groupId> <artifactId>postgresql</artifactId> <version>1.7.3</version> </dependency>

Even tried with different versions like 1.6.0 and 1.8.0 .

Is the issue still persists? or anything wrong at my code?

Hi @mthirani, do you have Docker installed? Which OS and Docker version?

@iCubeDm Thanks for your feedback, but your problem is unrelated, since it happens to @yissachar while starting the container, not inside the tests.

@kiview While using TestContainer, I thought it will create a virtual instance of Postgres container during the test and will destroy it once the test will complete.
Btw I do have a Docker installed where I am running Linux version 4.9.36-moby.
Do I need to have a Postgres there in docker?

This has been bugging me today and pretty sure it's related to this issue. I'm starting SpringBoot svc-intake as a GenericContainer and Postgres as a PostgresSqlContainer. Both containers are using the same network.

Postgres Network set to 440edef59718459ed7f7108dcfbce03e599ba1d57e3e8306f766818464f3a71a
[svc-intake:latest] - network 440edef59718459ed7f7108dcfbce03e599ba1d57e3e8306f766818464f3a71a

I can connect to Postgres from my IDE using jdbc:postgresql://localhost:33287/intake but svc-intake simply can't see it. Naturally I'm injecting the JDBC URL into svc-container, but during startup, the container reports

Connection to localhost:33287 refused

It appears as if there is something odd happening at the network level, but I'm not seeing it. No doubt I'm overlooking something obvious, but if there's any chance of a pointer, I'd appreciate it.

Simply injecting the containers and network as beans via Spring annotations.
TC 1.9.1, OSX, Docker for Mac 18.06.1 .

    @Bean(name = "postgres", initMethod = "start")
    @Lazy
    public GenericContainer postgresServiceContainer(@Autowired Network network,
                                                     @Value("${postgres.db:intake}") String db,
                                                     @Value("${postgres.user:flowable}") String user,
                                                     @Value("${postgres.pass:flowable}") String pass) {
        LOGGER.info ("Starting Postgres on network {}", network.getId());
        return new PostgreSQLContainer("postgres:9.6-alpine")
            .withDatabaseName(db)
            .withPassword(pass)
            .withUsername(user)
            .withExposedPorts(POSTGRES_PORT)
            .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("🐳 " + "postgres")))
            .withNetwork(network);
    }
// Have been mucking around with JdbcUrl() and Driver Classname values as per earlier comments in this issue. 
    @Bean(name = "svc-intake", initMethod = "start")
    public GenericContainer intakeServiceContainer(@Autowired Network network,
                                                   @Autowired PostgreSQLContainer postgres) {
        LOGGER.info("Postgres Network set to {}", postgres.getNetwork().getId());
        return javaServiceContainer("svc-intake", network)
            .withExposedPorts(10051, INTAKE_SERVICE_PORT)
            .withEnv("SPRING_DATASOURCE_URL", postgres.getJdbcUrl())
            .withEnv("SPRING_DATASOURCE_DRIVER-CLASS-NAME", postgres.getDriverClassName())
 }

// JavaSvcContainer is a wrapper around pull and create containers. it essentially winds up calling new GenericContainer(image)..withNetwork(network)

@monowai if you're running your service inside a container, you should use networks + networkAlias (eg "mypostgres") and connect with postgres://mypostgres:5432/... instead of using postgres.getJdbcUrl() (it's only valid on tests' host)

Hi @monowai,
the answer is actually quite simple.

The getters in Testcontainers assume you are running on the host, not inside the container. That means, all generated urls will contain the container host + mapped port. Of course, localhost inside the container means the container itself and that's why its failing.

In your case, you can have an even simpler setup, since you can leverage Docker network DNS.
Give your PostgreSQLContainer a name on the network (use withNetworkAlias("postgres") setter) and then you can use the following static url in your Spring service: postgres://postgres:5432

Edit:
Okay, @bsideup just beat me to it 😄

Hi,

I am testing the same Container and I receive the same error:

public class JUnit4PostgreSQLContainerTest {

    @ClassRule
    public static PostgreSQLContainer postgres =
            new PostgreSQLContainer();

    @Test
    public void testSimpleSQL() throws SQLException {
        postgres.withNetworkAliases("postgres");
        // HikariConfig
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(postgres.getJdbcUrl());
        hikariConfig.setUsername(postgres.getUsername());
        hikariConfig.setPassword(postgres.getPassword());

        HikariDataSource ds = new HikariDataSource(hikariConfig);
        Statement statement = ds.getConnection().createStatement();
        statement.execute("SELECT 1");
        ResultSet resultSet = statement.getResultSet();

        resultSet.next();
        assertEquals(1, resultSet.getInt(1));
    }
}

I tried with the idea about withNetworkAlias but it doesn't work with me.

My dependencies:

    testCompile ("org.testcontainers:postgresql:1.9.1")
    testCompile ("org.testcontainers:mysql:1.9.1")

System:

22:35:41.828 [main] INFO org.testcontainers.DockerClientFactory - Connected to docker: 
  Server Version: 17.03.2-ce
  API Version: 1.27
  Operating System: Ubuntu 16.04.4 LTS
  Total Memory: 7753 MB

Response:

22:35:54.659 [HikariPool-1 connection adder] DEBUG com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Cannot acquire connection from data source
org.postgresql.util.PSQLException: Connection to localhost:32799 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:280)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)

Juan Antonio

With the upgrade of the library 10.0.0:

java.lang.RuntimeException: 
Failed to get driver instance for jdbcUrl=jdbc:postgresql://localhost:32805/test

@jabrena I think that’s a different issue. In your case it seems that there is no Postgres driver library on your classpath. Testcontainers doesn’t provide a driver. If you do have the driver present then it’s another problem, and I’d ask you please to open a different issue.

Sent with GitHawk

@monowai @mthirani is this issue resolved for you? I’d like to close this ticket ASAP as it’s getting very confusing to follow what problem is being reported 😂

Sent with GitHawk

Hi @rnorth,

Yes, I replied in the typical behavior when You don' know how to continue. :)

Today, I will push my code in a POC that I am doing in a clean way. This is part of the learning curve :)

I continue in another issue.

Cheer

`add your ip in jdbc url
spring.datasource.url=jdbc:postgresql://12.45.67.12:5432/postgres

add this conf in pg_hba.conf file
host all all 0.0.0.0/0 md5`

this conf is working for me

Closing this issue, since the discussion started to sidetrack and involved many different topics and problems.

Please feel free to create new issues if the problem persist.

Was this page helpful?
0 / 5 - 0 ratings