Deploy Django app on Railway.app with Postgres
I need help deploying my Django app on the railway.app. I am still developing the app, but it is already in good shape, so I decided to try the deployment. It works fine on my local mac, I used Postgres as db, running into a docker. When I try to deploy it on the railway.app, I added a Dockerfile:
# Use an official Python runtime as a parent image
FROM python:3.10-slim
# Set environment variables to avoid interactive prompts during installation
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set the working directory
WORKDIR /app
# Install dependencies
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
# Copy the entire project into the container
COPY . /app/
# # Set the default Django app for commands
# ENV DJANGO_APP mywebsite
# Expose the port the app runs on
EXPOSE 8000
# Run the application
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Then I set up the environment variables on the dashboard for my django app, to connect with the postgress service:
- ${{Postgres.PGDATABASE}}
- ${{Postgres.PGUSER}}
- ${{Postgres.PGPASSWORD}}
- ${{Postgres.PGHOST}}
- ${{Postgres.PGPORT}} All shall be linked using the following piece of code in the settings.py:
os.environ.setdefault("PGDATABASE", "mydatabase")
os.environ.setdefault("PGUSER", "myuser")
os.environ.setdefault("PGPASSWORD", "mypassword")
os.environ.setdefault("PGHOST", "localhost")
os.environ.setdefault("PGPORT", "5432")
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ["PGDATABASE"],
'USER': os.environ["PGUSER"],
'PASSWORD': os.environ["PGPASSWORD"],
'HOST': os.environ["PGHOST"],
'PORT': os.environ["PGPORT"],
}
}
Then I use the railway.app CLI, and when I do something that does not involve the DB (e.g., railway run python manage.py collectstatic
), it works fine, but when I try to migrate, it shows an error such as:
django.db.utils.OperationalError: could not translate host name "postgres.railway.internal" to address: nodename nor servname provided, or not known
It seems that there is no connection with the DB. Am I missing something somewhere? Appreciate any attempt to help! :)