I have a docker app which has two containers. One is MySql and the other is some logic code which I have created a custom image of using a Dockerfile. For end to end testing, I wish to store some values in the database and then run the logic code image (Logic in golang). This is the docker-compose file I have currently:
version: '3'
networks:
docker-network:
driver: bridge
services:
database:
image: mysql
env_file:
- ./src/logic/environment-variables.env
ports:
- 3306:3306
healthcheck:
test: "mysql -uroot -p$$MYSQL_ROOT_PASSWORD $$MYSQL_DATABASE -e 'select 1'"
timeout: 20s
retries: 10
network:
docker-network
logic:
container_name: main-logic
build: ./src/logic/.
depends_on:
database:
condition: service_healthy
network:
docker-network
I cannot run this app as a whole as that would run the main as soon as the db is running. Instead, I want to start the db, store some values in it, then run the logic image. How can I do this in a test method?
Approaches considered:
Start up the mysql image separately from the test method and then store values in it.Then start the logic image and check the database for results. Is there a better way or a framework to use for this?
3
Answers
What you need here are database migrations. That should work as follows :
Consider this : https://github.com/golang-migrate/migrate
For your approach:
You can:
Use Makefile
with a sh script inside, that will execute all steps one by one.
Makefile:
Then execute
Use Testcontainers-Go
Testcontainers GitHub
It allows you to execute all steps in a go test method.
For your case you will have something like this:
just a draft code to catch up the idea:
Use Dockertest
Same as Testcontainers-Go,
just a draft code to catch up the idea:
You can do exactly what you say in the question: start the database, manually load the seed data, and start the rest of the application. Since your database has published
ports:
you can connect to it directly from the host without doing anything special.@advayrajhansa’s answer suggests using a database-migration system. If this was built into your image, you could
docker-compose run logic migrate ...
as the middle step. This runs an alternate command on the container you otherwise have defined in thedocker-compose.yml
file.