I am building a java spring mvc application in docker and dockefile build involves interacting with postgres container. Whenever i run docker-compose up
the step in dockerfile which interacts with the postrges sometimes fails with an exception
psql: could not translate host name "somePostgres" to address: Name or service not known
FAILED
FAILURE: Build failed with an exception.
DockerCompose file:
abcdweb:
links:
- abcdpostgres
build: .
ports:
- "8080:8080"
volumes:
- .:/abcd-myproj
container_name: someWeb
abcdpostgres:
image: postgres
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
container_name: somePostgres
The somePostgres seems to start very quickly and There is no late loading of postgres container problem. Currently i am running this in virtual box created by docker-machine. Unable to get error as it's not persistent.
PS: Added Dockerfile
FROM java:7
RUN apt-get update && apt-get install -y postgresql-client-9.4
ADD . ./abcd-myproj
WORKDIR /abcd-myproj
RUN ./gradlew build -x test
RUN sh db/importdata.sh
CMD ./gradlew jettyRun
Basically what this error means is that psql was unable to resolve the host name, try using the ip address instead.
https://github.com/postgres/postgres/blob/313f56ce2d1b9dfd3483e4f39611baa27852835a/src/interfaces/libpq/fe-connect.c#L2275-L2285
case CHT_HOST_NAME:
ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
&conn->addrlist);
if (ret || !conn->addrlist)
{
appendPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
ch->host, gai_strerror(ret));
goto keep_going;
}
break;
https://github.com/postgres/postgres/blob/8255c7a5eeba8f1a38b7a431c04909bde4f5e67d/src/common/ip.c#L57-L75
int
pg_getaddrinfo_all(const char *hostname, const char *servname,
const struct addrinfo *hintp, struct addrinfo **result)
{
int rc;
/* not all versions of getaddrinfo() zero *result on failure */
*result = NULL;
#ifdef HAVE_UNIX_SOCKETS
if (hintp->ai_family == AF_UNIX)
return getaddrinfo_unix(servname, hintp, result);
#endif
/* NULL has special meaning to getaddrinfo(). */
rc = getaddrinfo((!hostname || hostname[0] == '\0') ? NULL : hostname,
servname, hintp, result);
return rc;
}
I think links are not encouraged lately.
But, if you want to have services to communicate over network and explicitly here is the config:
You need to configure network an both services to attach to that network. It is something like:
networks:
network:
external: true
abcdweb:
links:
- abcdpostgres
build: .
ports:
- "8080:8080"
volumes:
- .:/abcd-myproj
container_name: someWeb
networks:
network: null
abcdpostgres:
image: postgres
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
container_name: somePostgres
networks:
network: null
In this way the service will communicate via the network with service names as adress.