After breaking my install of MySQL last year by trying to move from MariaDB to MySQL as I wanted to try JSON support out, I set out to find a better way of developing my Rails apps, instead of resorting to using something like Vagrant which would create separate VMs for each project.

Running Rails apps inside of Docker can be slow and cumbersome, so I found a way which I think is a better way; Running the databases in Docker instead.

I develop and maintain a number of Rails apps, ranging in Ruby and Rails versions. This means that some older Rails versions may not work properly with the new versions of MySQL or MariaDB.

To solve this, I’m now running my databases inside Docker.

This is an example docker-compose.dev.yml file for one of my apps.

version: "3.8"
services:
  mysql:
    container_name: florencebot-mysql
    image: mysql:8
    volumes:
      - mysql-data:/var/lib/mysql
    environment: 
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=app

  redis:
    container_name: florencebot-redis
    image: "redis:6.2-alpine"
    volumes:
      - redis-data:/var/lib/redis

volumes:
  mysql-data:
    driver: local
  redis-data:
    driver: local

I have an alias setup in my ZSH file for running this Docker Compose file in 1 command:

alias dcdev="docker compose -f docker-compose.dev.yml up"

I then use .env files with the dotenv-rails gem loaded in development and test environments to set the required env variables:

DATABASE_URL=mysql2://root:root@florencebot-mysql/app?pool=10&encoding=utf8mb4
REDIS_URL=redis://florencebot-redis/0

You may see that I’m using hostnames here. I’m using a Docker container called docker-hoster to set these in the hosts file. I have a docker-compose.yml file in /opt with the following contents:

---
version: "3.4"
services:
  hoster:
    image: dvdarias/docker-hoster
    container_name: hoster
    restart: always
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock
      - /etc/hosts:/tmp/hosts

This runs all the time so whenever I’m running multiple databases, it automatically adds the required IP to the hosts file.

This setup works really well for me and I hope it helps others.