3

What is the best practice for initializing a node microservice's tables in a postgres database ? Should it be on service start ?

I'm thinking of copying all the .sql files to the container (during docker build) + install psql into that container, and only run the .sql files during docker run before npm start. Does this make sense ?

I need to consider the fact that soon I will need to manage upgrading the database's tables for the microservice as well.

1
  • A) Declaratively - see answer by @VonC; B) Programmatically - you can have your own script load SQL and execute it (useful if you have a dynamic aspect to it). Commented May 16, 2016 at 14:09

1 Answer 1

2

One possibility is the one recommended by the Docker Postgres image:

How to extend this image

If you would like to do additional initialization in an image derived from this one, add one or more *.sql or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary).

After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files and source any *.sh scripts found in that directory to do further initialization before starting the service.

Sign up to request clarification or add additional context in comments.

4 Comments

So I'll need to add another docker file for the database ?
@georgehdd at least reuse the Dockerfile, but with the additional sql and scripts as described in that section: a new docker build will give you an extended image.
Usually there are going to be several instances (containers) for the microservice running. If each of them will try to initialize the microservice internal DB they all access you will have race condition. Better do it as part of your service orchestration service-init or your CI/CD.
@GabrielKohen Agreed. These days (two years later), this would be done with Kubernetes and an operator (as in medium.com/@cloudark/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.