'send_mail (smtp) from docker-compose (django + nginx + gunicorn)

I am trying to send email via Django. The mail should be sent to the user who would register to our system using Gmail.

I am also using docker-compse django, nginx, gunicorn and postgres.

This is my email configurations inside the django.

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True

EMAIL_HOST_USER = get_secret("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = get_secret("EMAIL_HOST_PASSWORD")
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

and docker-compose

version: '3.7'

services:
  web:
    build: 
      context: ./dj-psych
      dockerfile: Dockerfile.prod
    command: gunicorn config.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - static_volume:/home/app/web/static/
      - media_volume:/home/app/web/media/
    expose:
      - 8000
    env_file:
      - ./.env.prod
    depends_on:
      - db
  db:
    image: postgres:13.0
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    env_file:
      - ./.env.prod.db
  nginx:
    build: ./nginx
    volumes:
      - static_volume:/home/app/static
      - media_volume:/home/app/static
    ports:
      - server-port:80
    depends_on:
      - web

volumes:
  postgres_data:
  static_volume:
  media_volume:

nginx.conf

upstream config {
    server web:8000;
}

server {

    listen 80;

    location / {
        proxy_pass http://config;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /static/ {
        alias /home/app/static/;
    }

    location /media/ {
        alias /home/app/media/;
    }
}

I think the smtp server port (586) should be open in docker.

So I tried binding port web and nginx. But I can't.

how can i do it??

I tried.

from django.core.mail import EmailMessage
email = EmailMessage('subject', 'body', to=['[email protected]'])
email.send()

This is error message

OSError: [Errno 99] Cannot assign requested address

The assumption I made is this:

  1. The port (8000->80) entering Nginx from Django is responsible for both internal server port 8000 and SMTP port 587. Therefore, both server-related functions and the SMTP service of host port 8000 connected to Nginx must be open.
  2. Ports (8000->80) entering Nginx from Django must be assigned internal server port 8000 and SMTP port 587, respectively. There are two external connections (Django-Nginx-host), which should handle 8000 and 587 respectively, and the host port responsible for 587 should have SMTP service open. Can you tell me which one is the right way?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source