pgadmin을 사용해서 postgres를 다루어보려한다.

Docker 명령어 작성하기

DB와 pgadmin을 연결하기 위해 docker network를 생성해주어야한다.

docker network create pg-network

 

네트워크안에서 동작하는 컨테이너를 생성하기위해 다음 코드를 작성한다!

docker run -it \
    -e POSTGRES_USER="root" \
    -e POSTGRES_PASSWORD="root" \
    -e POSTGRES_DB="ny_taxi" \
    -v $(pwd)/ny_taxi_postgres_data:/var/lib/postgresql/data \
    -p 5432:5432 \
    --network=pg-network \
    --name pg-database \
    postgres:13

docker run -it \
    -e PGADMIN_DEFAULT_EMAIL="admin@admin.com" \
    -e PGADMIN_DEFAULT_PASSWORD="root" \
    -p 8080:80 \
    --network=pg-network \
    --name pgadmin \
    dpage/pgadmin4

 

  • --network=pg-network : docker 네트워크에 접속하기위해서 위에서 작성한 네트워크를 적용해주었다.

pgadmin 결과창

pgAdmin과 DB연결하기

이제 새 서버를 추가해서 만들었던 pg-database와 연결을 진행합니다.

 

연결된 DB의 테이블을 조회하면

 

다음과 같은 화면이 나오게 된다.


전체 코드는 Github에 업로드 하였습니다.

https://github.com/poriz/data-engineering-zoomcamp-poriz/tree/main/01-docker-terraform/introduce_to_docker

 

'Infra & Container > Docker' 카테고리의 다른 글

Docker - Docker compose  (0) 2024.03.21
Docker - 명령어 정리 & Volume  (0) 2024.03.21
Docker - Postgres > Data Ingestion  (0) 2024.03.21
Docker - Postgres  (0) 2024.03.20
Docker - Introduction to Docker  (0) 2024.03.18

Docker를 활용해서 PostgreSQL을 사용하고 데이터를 적재해보는 실습을 수행했다.

Docker 명령어 작성하기 - postgres

docker run -it \
    -e POSTGRES_USER="root" \
    -e POSTGRES_PASSWORD="root" \
    -e POSTGRES_DB="ny_taxi" \
    -v $(pwd)/ny_taxi_postgres_data:/var/lib/postgresql/data \
    -p 5432:5432 \
    postgres:13

 

코드를 뜯어보자.

  • -e POSTGRES_USER ... : POSTGRES에서 사용할 환경 변수를 입력해주었다.
  • -v &(pwd)/ny_taxi_...  : 호스트의 특정 위치를 볼륨으로 지정해준다. postgresql/data를 현재 디렉토리 하위의 nv_taxi_postgres_data와 연결해주었다.

실제로 확인한 결과!

  • -p 5432:5432 : PC의 포트를 도커 내부의 포트로 연결한다. 5432포트로 접속이 가능해진다. (앞이 현재pc에서 사용하는 포트)
  • 더 자세한 커멘드들은 다음 블로그를 참고하기를 바란다. https://www.daleseo.com/docker-run/

Postgres에 접속하기

다음 명령을 이용해서 연결을 진행하였다.

pgcli -h localhost -p 5432 -u root -d ny_taxi

 

뒤에 미리 앞에서 설정해둔 password를 입력하면 다음과 같은 화면을 볼 수 있다.

 

NewYork Taxi data 받아와서 처리하기

Data Source

연습용 데이터로 Taxi Data를 받아와 사용하였다.

 

TLC Trip Record Data - TLC

TLC Trip Record Data Yellow and green taxi trip records include fields capturing pick-up and drop-off dates/times, pick-up and drop-off locations, trip distances, itemized fares, rate types, payment types, and driver-reported passenger counts. The data use

www.nyc.gov

 

  • Yellow Taxi Trip Records를 받기위해 다음 명령어를 수행했다.
wget https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2023-01.parquet

 

Data 처리 및 SQL에 저장하기

jupyter notebook을 이용해서 데이터를 가져오고 postgreSQL과 연결해서 데이터를 업로드 하는 과정이다.

강의는 csv로 진행되었는데 ny_taxi_data가 parquet형식이여서 당황했지만 다행히 github에 parquet으로 진행하는 방법을 알려주어 참고해서 진행하였다.

 

1. 데이터 불러오기 - pyarrow 사용

import pyarrow.parquet as pq

# read metadata
pq.read_metadata('yellow_tripdata_2023-01.parquet')

file= pq.ParquetFile('yellow_tripdata_2023-01.parquet')
table = file.read()
table.schema

 

이렇게 읽어온 파일을 판다스 데이터 프레임으로 다시 변환하고 싶다면 다음 작업을 수행하면된다.

# convert to pandas
df = table.to_pandas()

 

2. postgresql 연결하기

sqlalchemy를 사용해서 postgresql과 연결한다. (sqlalchemy는 신인가...?)

# connect PostgreSQl with sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('postgresql://root:root@localhost:5432/ny_taxi')
engine.connect()
  • pandas에는 테이블을 쉽게 만들기 위해서 데이터 프레임을 테이블 생성코드로 변환해주는 기능이 있다!
    (그러나 후에 to_sql을 하는 경우에는 테이블이 없어도 생성되어 크게 쓸일은 없었다..)
# Generate CREATE SQL
print(pd.io.sql.get_schema(df, name='yellow_taxi_data',con=engine))

3. batch size를 설정해서 insert하기

배치 사이즈를 10,000으로 설정해서 반복해서 insert를 수행한다.

# Insert values into the table
t_start = time()
count = 0

for batch in file.iter_batches(batch_size=100000):
    count+=1
    batch_df = batch.to_pandas()
    print(f'inserting batch {count} ...')
    b_start = time()

    batch_df.to_sql(name='ny_taxi_data', con=engine, if_exists='append')
    b_end = time()
    print(f'inserted, time taken {b_end-b_start:10.3f} seconds.\n')

t_end = time()
print(f'Completed. Total time taken was {t_end-t_start:10.3f} seconds for {count} batches.')

 

배치 수행 결과

이제 postgresql에 접속해서 데이터를 확인하면?

 

정상적으로 잘 동작한 것을 확인 가능하다.

 


전체 코드는 Github에 업로드 하였습니다.

https://github.com/poriz/data-engineering-zoomcamp-poriz/tree/main/01-docker-terraform/introduce_to_docker

 

'Infra & Container > Docker' 카테고리의 다른 글

Docker - Docker compose  (0) 2024.03.21
Docker - 명령어 정리 & Volume  (0) 2024.03.21
Docker - Postgres > Data Ingestion  (0) 2024.03.21
Docker - Postgres > pgadmin  (0) 2024.03.20
Docker - Introduction to Docker  (0) 2024.03.18

Docker Image 생성하기

1. Dockerfile 작성하기

도커 이미지를 생성하기 위해 Dockerfile을 작성해야한다. 간단한 작성 과정과 함께 사용되는 명령들을 정리한다.

FROM python:3.9

RUN pip install pandas

WORKDIR /app
COPY pipeline.py pipeline.py

ENTRYPOINT ["python", "pipeline.py"]

 

  • FROM: 기반이 되어주는 이미지를 선택한다. (docker-hub에 있음!!)
    > 내가 생성한 이미지는 python:3.9를 기본 이미지로 가져와 생성되는 이미지이다!
  • RUN: 이미지 생성시에 초기에 동작할 명령들을 입력한다.
    > pip를 사용해서 pandas 모듈을 설치!
  • WORKDIR: 작업할 디렉토리를 설정한다.
  • COPY: 로컬에서 docker에 복사할 파일을 정의한다.
  • ENTRYPOINT: 컨테이너 시작시에 실행되는 기본 명령을 정의한다.
    > python으로 pipeline.py를 실행하라는 뜻!! ENTRYPOINT에 추가로 인자전달을 위해서 docker 실행 시에 인자를 같이 넘겨줄 수 있다. 아래 예시문을 추가하였다.!
docker run -it test:pandas your_day_value

 

2. pipeline.py 작성하기

import pandas as pd
import sys
# some fancy stuff with pandas

# argv[0] = name of the file
day = sys.argv[1]

print(f'job finished successfully day= f{day}')

 

인자를 받아서 구문을 출력하는 간단한 파일을 생성하여 테스트 해보았다.

 

3. 이미지 빌드 및 실행

  • 빌드 명령: -t를 이용해서 tag를 부여하고 .을 이용해서 현재 디렉토리를 빌드 컨텍스트의 위치로 지정한다.
    즉, docker build 명령을 실행하는 위치에서 Dockerfile을 찾고, 해당 디렉터리와 그 하위 디렉터리에 있는 파일들을 이미지 빌드에 사용할 수 있는 자원으로 간주한다.
docker build -t test:pandas .

 

  • 이미지 실행(컨테이너 생성)
    : 도커 컨테이너를 실행하고 생성된 컨테이너에 인자를 전달한다.
    -it 옵션은 Docker 컨테이너를 대화형 모드로 실행하며, 터미널 입력을 컨테이너에 연결한다!
    이 옵션은 일반적으로 컨테이너 내에서 명령어를 실행하거나, 쉘에 접근하여 컨테이너를 대화식으로 조작할 필요가 있을 때 사용된다.
docker run -it test:pandas 2024-03-18

 


Codes: https://github.com/poriz/data-engineering-zoomcamp-poriz/tree/main/01-docker-terraform/introduce_to_docker

'Infra & Container > Docker' 카테고리의 다른 글

Docker - Docker compose  (0) 2024.03.21
Docker - 명령어 정리 & Volume  (0) 2024.03.21
Docker - Postgres > Data Ingestion  (0) 2024.03.21
Docker - Postgres > pgadmin  (0) 2024.03.20
Docker - Postgres  (0) 2024.03.20

+ Recent posts