Marco Afonso
Marco Afonso

Reputation: 316

Docker container for app tests with postgres database

I'm new to Docker.

I'm trying to run my node app tests in a Docker container. I want to run the tests with a real postgres db. I'm creating this container with the following Dockerfile:

# Set image
FROM postgres:alpine
# Install node latest
RUN apk add --update nodejs nodejs-npm
# Set working dir
WORKDIR .
# Copy the current directory contents into the container at .
ADD src src
ADD .env.testing .env
ADD package.json .
ADD package-lock.json .

# Run tests
CMD npm install && npm run coverage
  1. From the image docs, when I run the container with:

    $ docker run build-name -d postgres

I see that the container takes time to start postgresql service.

  1. When I run the container without the "-d postgres" param:

    $ docker run build-name

The service does not start and the tests fail due to "could not connect to server".


Questions:

A. How can I run the tests AFTER the postgresql service starts?

B. I saw some examples using docker-composer but can I do this without composer?

Thanks

Upvotes: 1

Views: 2096

Answers (2)

Marco Afonso
Marco Afonso

Reputation: 316

Thanks to @Bogdan I found the complete solution:

Dockerfile should be:

# Set image
FROM postgres:alpine
# Install node latest
RUN apk add --update nodejs nodejs-npm
# Set working dir
WORKDIR .
# Copy the current directory contents into the container at .
ADD src src
ADD .env.testing .env
ADD package.json .
ADD package-lock.json .
# Install
RUN npm install

# Init container
CMD psql -U postgres -c "SELECT 1;" postgres

Build container:

$ docker build -t test .

Run container:

$ docker run --name startedtest -d test -d postgres

Run tests after conatiner is running:

$ docker exec startedtest some_create_schema_script && npm run coverage

Upvotes: 3

b0gusb
b0gusb

Reputation: 4731

If the goal is just to run the tests in the Postgres container, one solution could be to install NodeJs in your postgres:alpine derived image and run the container normally. Once the database is up, you can run npm using docker exec like this:

docker exec <container_id> npm run coverage

Upvotes: 2

Related Questions