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

SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
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
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
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
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
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
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement