Implement a dockerized node service and postgres image with sample data
To implement a dockerized node and postgres image, let’s take the following steps.
Create a package.json file with the following content:
We will use this to spit out a simple node application as a docker image in our container.
3. Create a init.sql file with the following content:
We will run this sql file when we create a postgres docker image. This script will initialize a todo table with some default value.
4. Create a docker-compose.xml with the following content:
In this file, we specify two images to be installed: a postgres image and the app we are building. Notice there is a volume section under the db service section. When we run “docker-compose up” it will run init.sql script as well.
5. Create a server.js file with the following content:
With this file, we will instiantiate an express server running as a docker image on our container when we do “docker-compose up”. This express server exposes two endpoint: one to get data from the todos table and another one to insert data into the todos table.
6. Now run “docker-compose up”. This will run “docker build” behind the scene and install the postgres image as well as our express server.
If you run docker ps you should see two docker containers running: one called todo_app, and another called todo_db. If you want to stop your application, simply running the following steps:
- docker-compose down
- docker rmi -f $(docker images -aq)
- docker rm $(docker ps -aq)
This will stop running the containers and remove any containers/images as needed to.