8강에서 postgresql 접속이 안되네요
138
작성한 질문수 1
몇시간째 이유를 모르겠네요. 아래와 같은 에러로 airflow에서 postresql로 접속이 안되는것 같습니다.
File "/opt/airflow/dags/dags_python_with_postgres.py", line 17, in insrt_postgreswith closing(psycopg2.connect(host=ip, dbname=dbname, user=user, password=passwd, port=int(port))) as conn:^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/home/airflow/.local/lib/python3.12/site-packages/psycopg2/__init__.py", line 122, in connectconn = connect(dsn, connectionfactory=connection_factory, **kwasync)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^psycopg2.OperationalError: connection to server at "172.28.0.3", port 5432 failed: Connection timed outIs the server running on that host and accepting TCP/IP connections?
from airflow import DAG
import pendulum
from airflow.operators.python import PythonOperator
with DAG(
dag_id='dags_python_with_postgres',
start_date=pendulum.datetime(2023,4,1, tz='Asia/Seoul'),
schedule=None,
catchup=False
) as dag:
def insrt_postgres(ip, port, dbname, user, passwd, **kwargs):
import psycopg2
from contextlib import closing
with closing(psycopg2.connect(host=ip, dbname=dbname, user=user, password=passwd, port=int(port))) as conn:
with closing(conn.cursor()) as cursor:
dag_id = kwargs.get('ti').dag_id
task_id = kwargs.get('ti').task_id
run_id = kwargs.get('ti').run_id
msg = 'insrt 수행'
sql = 'insert into py_opr_drct_insrt values (%s,%s,%s,%s);'
cursor.execute(sql,(dag_id,task_id,run_id,msg))
conn.commit()
insrt_postgres = PythonOperator(
task_id='insrt_postgres',
python_callable=insrt_postgres,
op_args=['172.28.0.3', '5432', 'emuce', 'emuce', 'emuce']
)
insrt_postgres답변 2
0
안녕하세요 답변 감사합니다. 근데 아래처럼 말씀주신대로 했는데도 안되네요..
emuce-postgres-custom-1 : 조회결과
docker inspect emuce-postgres-custom-1 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAddress": "172.28.0.3",
emuce-airflow-worker-1 : 조회결과
docker inspect emuce-airflow-worker-1 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAddress": "172.28.0.8",
이렇게 결과가 나옵니다.
nc -v 172.28.0.3 5432 : 조회결과
Connection to 172.28.0.3 5432 port [tcp/postgresql] succeeded!
0
음 nc -v 까지 성공했으면 네트워크 상 문제가 없어보입니다.
그럼 worker 컨테이너 안에서 postgres 연결하는 파이썬 구문을 직접 수행해보실래요?
worker 컨테이너 안에서 python 치시고 아래 처럼 진행해보면 됩니다.
import psycopg2
conn = psycopg2.connect(host='172.28.0.3', dbname='emuce', user='emuce', password='emuce', port=5432)
cur = conn.cursor()여기까지 진행해서 이상없으면 파이썬 라이브러리 문제는 없는 걸로 판단 가능합니다.
한번 해보시고 남겨주세요!
0
안녕하세요 임원선님!
docker-compose.yaml 파일은 잘 작성하신 것 같습니다.
그런데 왜 안되는지는 이제부터 확인을 좀 해봐야겠네요.
우선 로컬 컴퓨터에서 postgres_custom 컨테이너랑 worker 컨테이너랑 IP 좀 확인해볼께요.
sudo docker ps 해서 컨테이너 이름 각각 확인하시고
docker inspect {postgres_custom 컨테이너명} | grep IPAddress
docker inspect {worker 컨테이너명} | grep IPAddress이렇게 해서 현재 떠 있는 컨테이너 IP 각각 확인해보실래요?
그리고 worker 컨테이너에서 postgres_custom 컨테이너의 IP:Port로 접속할 수 있는지 직접 명령어로 확인해볼 수 있습니다.
sudo docker exec -it {worker 컨테이너명} bash 이렇게 해서 워커 컨테이너에 진입하시고 아래처럼 해보세요.
nc -v 172.28.0.3 5432이렇게 명령했을 때 워커가 postgres_custom과 연결이 가능하면 아래처럼 Connected 라고 뜹니다.
이게 안되면 일단 컨테이너간 네트워크 연결이 안되는 상황이라고 보시면 됩니다.
★ 답글 달아주신 docker-compose.yaml 파일 내용은 지워주시는게 좋겠습니다 (SMTP 연결 키가 들어가있어요)
0
이것도 문제없이 되는 것 같습니다...
airflow에서 뭔가를 제가 잘못하고 있는걸까요?
-----------------------------------
default@2d96de3dc427:/opt/airflow$ python
Python 3.12.9 (main, Feb 6 2025, 22:37:05) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
d='emuce', port=5432)
cur = conn.cursor()>>> conn = psycopg2.connect(host='172.28.0.3', dbname='emuce', user='emuce', password='emuce', port=5432)
>>> cur = conn.cursor()
>>>
아 참 이상하네요...
0
그럼 안될 이유가 없는데 이상하네요.
sudo docker compose down
sudo docker compose up
재기동하고 dag 수행해도 동일한가요?
그리고 마지막으로 아까 컨테이너 안에서 cur 까지 얻으셨으면
cur.execute('insert into py_opr_drct_insrt values ("a","b","c","d")')
conn.commit()
이렇게 insert 까지 한번 수행해보실래요?
0
죄송합니다. 답변이 늦었습니다.말씀주신대로 했더니 에러가 나기는 합니다. 뭐가 문제일까요?
>>> import psycopg2
'emuce', password='emuce', port=5432)
cur = conn.cursor()>>> conn =
psycopg2.connect(host='172.28.0.3', dbname='emuce', user='emuce', password='emuce', port=5432)
>>> cur = conn.cursor()
>>> cur.execute('insert into py_opr_drct_insrt values ("a","b","c","d")')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
psycopg2.errors.UndefinedColumn: column "a" does not exist
LINE 1: insert into py_opr_drct_insrt values ("a","b","c","d")
0
흠.. 일단 시도해주신 부분에 대한 에러는 DB까지 접속한 이후에 발생한 에러라 DB 접속 자체는 잘 됐다고 볼 수 있는 부분입니다.
따라서 worker --> custom_postres DB에 대한 접속은 아무 문제없이 잘 되고 있는데 DAG에서만 안되고 있는게 좀 희한한 문제네요.
죄송하지만 지금 작성된 docker-compose.yaml 내 이메일 인증부분만 제거하셔서
저한테 메일로 좀 보내주시겠어요?
hjkim_sun@naver.com 입니다.
pykrx 회원제 전환으로 인한 실습 불가
0
114
2
수료증 발급
0
84
3
에러 발생 관련 질문드립니다.
0
83
2
vscode 작업화면에 오류가 발생하지 않습니다.
0
69
2
plugins 폴더 생성
0
75
2
WSL에서 git push 가 안되요 ㅠ
0
114
2
chatGPT&Airflow로 블로그 자동 포스팅하기 는 Deprecated 가 필요합니다.
0
66
2
github에 회원가입이 안되는데 원인이 뭔지 모르겠어요 ㅠ
0
733
2
설치중인데 venv를 꼭 써야할까요?
0
126
2
설치 버전 관련 질문입니다.
0
68
1
우분투 버전 다운받아야하는데 어떤걸로 설치해야할까요?
0
62
1
DAG 만들기 중 airflow 패키지 로드 에러
0
106
2
3.0에서도 수업노트가 성립하는지 확인 부탁드립니다!
0
95
3
task_id 사용법이 뭔가 바뀐 것 같습니다.
0
76
3
email operator 오류 관련
0
66
2
plugins 폴더 관련
0
100
2
bash operator 관련 문의입니다
0
78
3
스케쥴러 - DAG 파싱 부하 줄이는 과정 질문
0
79
2
Dags refresh 주기 관련 질문
0
125
2
wsl 관련 질문입니다.!
0
75
2
macOS에서 docker 설치
0
94
2
템플릿 변수에 대한 오류
0
61
2
custom_image 디렉토리 문의드립니다.
0
54
2
ETL 인터뷰 관련 문의
0
103
2





