How you would configure elixir app with ecto to connect with postgres on host machine?

I’ve added ecto to my Elixir app. On host it’s running fine, because ecto can connect to local db. But I don’t understand, what i need to do, if this app running in docker container.

I’m getting this error:
11:42:31.536 [error] Postgrex.Protocol (#PID<0.249.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused - :econnrefused

And I understand, that docker container with my app doesn’t have postgresql at localhost inside. But i don’t understand, how configure this.

P.S. I’m trying to learn Docker, Elixir, Ecto, Postgresql.

My app on github, branch - main, not master.

Instead of localhost connect to whatever the hostname of postgres is in your docker setup. What that is depends on your general setup – postgres within docker or postgres on the host running docker – as well as potentially the specific name you gave things.

My postgres runs at host machine, not in container. Where i can find hostname of postgres?

1 Like

That works!

config :echo, Echo.Repo,
  database: "echo_db",
  username: "postgres",
  password: "postgres",
  hostname: "host.docker.internal"

Thank you, but now i can’t start my app localy on machine. How can i split configuration of ecto for docker, and for local using?

https://hexdocs.pm/elixir/Config.html#import_config/1

Maybe you could do stuff like this in your dev.exs

get_db_host = fn -> 
  if File.exists?("/.dockerenv") do
    "host.docker.internal"
  else
    "pg host outside docker"
  end
end

config :echo, Echo.Repo
    ...
    hostname: get_db_host.()

But it’s also possible to read it from the environment by using;

config :echo, Echo.Repo
   ...
   database: System.get_env("PGHOST", "host.docker.internal")

then outside of the docker you have to set PGHOST before starting things up.

1 Like

I’ve find another way of solving this problem.

Uncommented this line from config/config.exs

import_config "#{config_env()}.exs"

Added docker.exs with

import Config


config :echo, Echo.Repo,
  database: "echo_db",
  username: "postgres",
  password: "postgres",
  hostname: "host.docker.internal"

Added to up of Dockerfile

ENV MIX_ENV docker

Yeah, i have read this before, but don’t understand how use this. Now i know

Yeah this is even another way of doing it and maybe the cleanest way.

Great you found a good solution! Happy elixiring! :slight_smile: