I’m working on building docker containers for a Ruby-on-Rails project I’m currently working on, so that I can develop this project using the remote feature of Visual Studio Code. This project should still continue to work without using docker containers, so I cannot make breaking changes to the existing code that would compromise this.
The application server (Rails) needs to connect to a MySQL database that’s running in a separate container. The database container is named db
, and I can connect from the application container to this container by using the db
hostname.
The database.yml
config file for rails defines how to connect to the database, but this is where my problem is situated. I don’t want to change the host to db
instead of localhost
as this would mean that regular users (that do not use Docker containers) will no longer be able to connect to the database without changing this file. How can I somehow start or change my docker config so that db
is accessible as localhost
instead of db
inside of the application container?
database.yml
:
default: &default
adapter: mysql2
username: ****
password: ****
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: ****
# setup local port forwarding for this to work
host: db
port: 3306
docker-compose.yml
:
version: '3.7'
services:
db:
build: ./unipept-db
environment:
MYSQL_ROOT_PASSWORD: ****
MYSQL_DATABASE: ****
MYSQL_USER: ****
MYSQL_PASSWORD: ****
restart: always
ports:
- "3306:3306"
hostname: mysql
phpmyadmin:
depends_on:
- db
image: phpmyadmin/phpmyadmin
ports:
- '8080:80'
environment:
PMA_HOST: db
MYSQL_ROOT_PASSWORD: ****
restart: always
app:
depends_on:
- db
build: ./unipept-application
command: sleep infinity
ports:
- '5000:5000'
volumes:
- ~/.gitconfig:/root/.gitconfig
- ..:/workspace
2
Answers
user
network_mode: "host"
in yourAPP
config then you can call theDB
from yourAPP
usinglocalhost:PORT
PS: Published ports are discarded when using host network mode
If you make it an environment variable in your
database.yml.erb
file, it will be configurable. You even already have an example of this. You can set:In development, just don’t set the environment variable, and it will use
localhost
. In a Docker environment, do set it, and it will use that hostname.You should also pass things like database credentials the same way.