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

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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 ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

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
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement