arialblack14

arialblack14

Postgrex.Protocol (#PID<0.2424.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused - :econnrefused

Hello everyone,

I am learning Phoenix/Elixir and I am trying to dockerize my app so that I can deploy to AWS, but I keep getting all kinds of errors.

I am getting this error:

Recreating myapp_web_1_f59b1c3a118c ... done
Attaching to myapp_web_1_f59b1c3a118c
web_1_f59b1c3a118c | "ecto://postgres:alejandro1@localhost/appexo_prod"
web_1_f59b1c3a118c | 18:45:11.435 [error] Postgrex.Protocol (#PID<0.2424.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused - :econnrefused
...
web_1_f59b1c3a118c | 18:45:11.438 [error] Postgrex.Protocol (#PID<0.2417.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused - :econnrefused
web_1_f59b1c3a118c | 18:45:11.443 [info] Running MyappWeb.Endpoint with cowboy 2.6.3 at :::4000 (http)
web_1_f59b1c3a118c | 18:45:11.443 [info] Access MyappWeb.Endpoint at http://localhost:4000
^CGracefully stopping... (press Ctrl+C again to force)
Stopping myapp_web_1_f59b1c3a118c   ... 
Killing myapp_web_1_f59b1c3a118c    ... done

The Endpoint is wrong and connection is refused.
Here is my prod.exs

use Mix.Config

config :myapp, MyappWeb.Endpoint,
  http: [:inet6, port: System.get_env("PORT") || 4000],
  url: [host: "localhost", port: System.get_env("PORT")],
  cache_static_manifest: "priv/static/cache_manifest.json",
  secret_key_base: System.get_env("SECRET_KEY_BASE"),
  server: true,
  root: "."

# Do not print debug messages in production
config :logger, level: :info

# Configure your database
config :myapp, Myapp.Repo,
  adapter: Ecto.Adapters.Postgres,
  # hostname: System.get_env("DATABASE_HOST"),
  # username: System.get_env("DATABASE_USER"),
  # password: System.get_env("DATABASE_PASS"),
  # database: System.get_env("DATABASE_NAME"),
  url: System.get_env("DATABASE_URL"),
  pool_size: 10

# import_config "prod.secret.exs"

My docker-compose.yml

version: '3.5'

services:
  web:
    image: "myapp:latest"
    ports:
      - "80:4000" # In our .env file above, we chose port 4000
    env_file:
      - config/docker.env

My config/config.exs

use Mix.Config

config :myapp,
  ecto_repos: [Myapp.Repo]

# Configures the endpoint
config :myapp, MyappWeb.Endpoint,
  url: [host: "localhost"],
  secret_key_base: "RXyklAFqTajbz7dePdeEHa/sLLbMORcUeY/GshZsKnXJIZ7eSTnKQq22DRoCkTO/",
  render_errors: [view: AppexoWeb.ErrorView, accepts: ~w(json)],
  pubsub: [name: Appexo.PubSub, adapter: Phoenix.PubSub.PG2]
.........
import_config "#{Mix.env()}.exs"

My Dockerfile:

# The version of Alpine to use for the final image
# This should match the version of Alpine that the `elixir:1.7.2-alpine` image uses
ARG ALPINE_VERSION=3.9

FROM elixir:1.8.2-alpine AS builder

# The following are build arguments used to change variable parts of the image.
# The name of your application/release (required)
ARG APP_NAME=myapp
# Database Url
ARG DATABASE_URL=ecto://postgres:xxxxxxxxxx@localhost/my_db
# The version of the application we are building (required)
ARG APP_VSN=0.1.0
# The environment to build with
ARG MIX_ENV=prod
# Set this to true if this release is not a Phoenix app
ARG SKIP_PHOENIX=false
# If you are using an umbrella project, you can change this
# argument to the directory the Phoenix app is in so that the assets
# can be built
ARG PHOENIX_SUBDIR=.

ENV SKIP_PHOENIX=${SKIP_PHOENIX} \
    APP_NAME=${APP_NAME} \
    APP_VSN=${APP_VSN} \
    MIX_ENV=${MIX_ENV} \
    DATABASE_URL=${DATABASE_URL}

# By convention, /opt is typically used for applications
WORKDIR /opt/app

# This step installs all the build tools we'll need
RUN apk update && \
  apk upgrade --no-cache && \
  apk add --no-cache \
    nodejs \
    yarn \
    git \
    build-base && \
  mix local.rebar --force && \
  mix local.hex --force

# This copies our app source code into the build container
COPY . .

RUN mix do deps.get, deps.compile, compile

# This step builds assets for the Phoenix app (if there is one)
# If you aren't building a Phoenix app, pass `--build-arg SKIP_PHOENIX=true`
# This is mostly here for demonstration purposes
RUN if [ ! "$SKIP_PHOENIX" = "true" ]; then \
  cd ${PHOENIX_SUBDIR}/assets && \
  yarn install && \
  yarn deploy && \
  cd - && \
  mix phx.digest; \
fi

RUN \
  mkdir -p /opt/built && \
  mix distillery.release --verbose && \
  cp _build/${MIX_ENV}/rel/${APP_NAME}/releases/${APP_VSN}/${APP_NAME}.tar.gz /opt/built && \
  cd /opt/built && \
  tar -xzf ${APP_NAME}.tar.gz && \
  rm ${APP_NAME}.tar.gz

# From this line onwards, we're in a new image, which will be the image used in production
FROM alpine:${ALPINE_VERSION}

# The name of your application/release (required)
ARG APP_NAME=myapp
# Database Url
ARG DATABASE_URL=ecto://postgres:xxxxxxx@localhost/mydb

RUN apk update && \
    apk add --no-cache \
      bash \
      openssl-dev

ENV REPLACE_OS_VARS=true \
    APP_NAME=${APP_NAME} \
    DATABASE_URL=${DATABASE_URL}

WORKDIR /opt/app

COPY --from=builder /opt/built .

CMD trap 'exit' INT; DATABASE_URL=${DATABASE_URL} /opt/app/bin/${APP_NAME} foreground

My repo.ex

defmodule Myapp.Repo do
  use Ecto.Repo,
    otp_app: :myapp,
    adapter: Ecto.Adapters.Postgres

  def init(_type, config) do
    database_url = System.get_env("DATABASE_URL")
    IO.inspect(database_url)

    if database_url == nil do
      {:ok, config}
    else
      {:ok, Keyword.put(config, :url, database_url)}
    end
  end
end

rel/config.exs

...

environment :prod do
  set include_erts: true
  set include_src: false
  set cookie: :"..................."
  # set vm_args: "rel/vm.args"
end

release :myapp do
  set version: current_version(:appexo)
  set applications: [
    :runtime_tools
  ]

  set config_providers: [
    {Distillery.Releases.Config.Providers.Elixir, ["${RELEASE_ROOT_DIR}/etc/config.exs"]}
  ]
  set overlays: [
    {:copy, "rel/config/config.exs", "etc/config.exs"}
  ]
end

And my rel/config/config.exs

use Mix.Config

config :myapp, Myapp.Repo,
  # username: System.get_env("DATABASE_USER"),
  # password: System.get_env("DATABASE_PASS"),
  # database: System.get_env("DATABASE_NAME"),
  # hostname: System.get_env("DATABASE_HOST"),
  url: System.get_env("DATABASE_URL"),
  pool_size: 10

port = String.to_integer(System.get_env("PORT") || "8080")
config :appexo, Appexo.Endpoint,
  http: [port: port],
  url: [host: "localhost", port: port],
  root: ".",
  secret_key_base: System.get_env("SECRET_KEY_BASE")

Also docker.env

HOSTNAME=localhost
SECRET_KEY_BASE="u1QXlca4XEZKb1o3HL/aUlznI1qstCNAQ6yme/lFbFIs0Iqiq/annZ+Ty8JyUCDc"
DATABASE_HOST=db
DATABASE_USER=postgres
DATABASE_PASS=xxxxxxx
DATABASE_NAME=my_db
DATABASE_URL=ecto://postgres:xxxxxxx@localhost/my_db
PORT=4000
LANG=en_US.UTF-8
REPLACE_OS_VARS=true

I have tried a lot of things… What am I doing wrong??

Marked As Solved

arialblack14

arialblack14

@jola @idi527 Thank you bothfor your help!

I thought I could access the host database from inside a container. Both your suggestions helped a lot.

For linux since host.docker.internal is not working, all I had to do was add to my docker-compose.yml file this:

services:
  web:
   ..........
    network_mode: "host"

Also Liked

idi527

idi527

What exactly doesn’t work? What do you expect, and what happens instead? Do you mean the app can’t connect to the database?

Note that if your app is running within a container, it might not be able to see the database running on the host at ecto://...@localhost:5432/db_name unless you use --network="host" flag or something similar. If your database is also running in a container, you’d need to create a bridge network for it and your app or something like that.

jola

jola

You’ve commented out the line in the database config that would set the option to what you have in the docker.env, so it uses the default localhost instead of the docker.env db. Your docker image doesn’t have postgres running on localhost, it is running in a different container.

Where Next?

Popular in Questions Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement