Deploy and start a docker postgres db container with ansible

phil
phil
Jul 30, 2017 · 2 min read

I am tired of setting up db servers like postgres for every new project I start. I recently stumbled upon ansible as an automation tool. So I thought it might be nice to use an ansible playbook just in order to launch a postgres db as a docker container.

So this my current playbook

— -
- hosts: local
gather_facts: false
become: yes

tasks:
— name: ensure repository key is installed
apt_key:
id: “58118E89F3A912897C070ADBF76221572C52609D”
keyserver: “hkp://p80.pool.sks-keyservers.net:80”
state: present

- name: Bootstrap | Install python 2.x
raw: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python-minimal python-pip

- name: install certain python modules for docker
pip:
name: “{{ item.name }}”
version: “{{ item.version }}”
state: present
with_items:
— { name: docker, version: 2.0.0 }
— { name: docker-py, version: 1.10.6 }

- name: ensure docker registry is available
# For Ubuntu 14.04 LTS, use this repository:
# apt_repository: repo=’deb https://apt.dockerproject.org/repo ubuntu-trusty main’ state=present
# For Ubuntu 16.04 LTS, use this repo instead:
apt_repository: repo=’deb https://apt.dockerproject.org/repo ubuntu-xenial main’ state=present

- name: ensure docker and dependencies are installed
apt: name=docker-engine update_cache=yes

- name: pull image postgres9.6.0
docker_image:
name: postgres
state: present
— name: add user mod
command: sudo usermod -aG docker ubuntu

- name: ensure a container is running
docker_container:
name: postgres_db
state: started
restart_policy: always
image: postgres:9.6.0
pull: false
detach: yes
ports:
— “5432:5432”

- name: docker started
service: name=docker state=restarted

Nevertheless it took me quite some time to get the docker container running. It exited with status 137 (Exited (137)) all the time unless I added the restart_poliy -> restart_policy: always

Just in case you are running on vagrant or virtualbox. You need to change the port forwarding of the vm. Make sure the network is running in NAT mode and ensure that the postgres port (5432) is forwarded.

phil

Written by

phil

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade