Skip to main content

Docker-compose Basics

Dockerfile

Automating the process of downloading the image and starting the container on specified port and then setting up the database with specific script can be achieved with docker-compose.yml which written in yaml file. Below is a sample file to download postgres image and setup the database. The sql script should be provide in the sql_scripts directory. Follow the formatting required for yaml specification

version: "3"

services:
postgres:
image: "postgres:14.5"
restart: always
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: users
logging:
options:
max-size: 10m
max-file: "3"
ports:
- "5432:5432"
volumes:
- ./postgres-data:/var/lib/postgresql/data
- ./sql_scripts/create_user_tables.sql:/docker-entrypoint-initdb.d/create_user_tables.sql

save the file as stack.yml

execute the docker-compose.yml file

docker-compose -f stack.yml up

docker-compose mongo

Example of docker-compose.xml file mongodb image on docker hub

# Use root/example as user/password credentials
version: "3.1"

services:
mongo:
image: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example

mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: example
ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/

deploy with docker-compose

docker-compose -f stack.yml up

deploy with docker

docker stack deploy -c stack.yml mongo

container interactive shell

docker exec -it some-mongo bash