IT기술/cloud, docker에 해당하는 글 3

AWS boto3 시작하기

IT기술/cloud, docker|2021. 1. 16. 00:24

2020-01-10 작성

 

boto3은 AWS를 python 코드로 사용할 수 있게 해주는 라이브러리이다.
처음 시작은 boto3의 QuickStart를 보고 하는게 빠르다.

 

Boto is the Amazon Web Services (AWS) SDK for Python. It enables Python developers to create, configure, and manage AWS services, such as EC2 and S3. Boto provides an easy to use, object-oriented API, as well as low-level access to AWS services.]

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html

 

1. boto3을 설치한다.

pip install boto3

2. AWS > iam > 사용자 > 보안 자격 증명에서 액세스 키 생성

 

3. credentials 설정파일 입력

touch ~/.aws/credentials
vim ~/.aws/credentials

### 다음 부분을 입력한다.
[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

4. region 설정파일 입력

touch ~/.aws/config
vim ~/.aws/config

### 다음 부분을 입력한다. ap-northeast-2는 서울 리전임
[default]
region=ap-northeast-2

5. s3 bucket 목록 가져오기(여기부터는 python 파일을 만들어서 python으로 실행하면 된다.)

import boto3
 
# Let's use Amazon S3
s3 = boto3.resource('s3')

# Print out bucket names
for bucket in s3.buckets.all():
	print(bucket.name)

6. 파일 업로드 하기

# Upload a new file
data = open('test.parquet', 'rb')
s3.Bucket('my-bucket').put_object(Key='test.parquet', Body=data)

7. parquet 파일을 s3select로 query해보고 출력하기

s3 = boto3.client('s3')
response = s3.select_object_content(
    Bucket=bucket_name,
    Key=file_name,
    ExpressionType='SQL',
    Expression="select * from s3object s limit 10",
    InputSerialization = {'Parquet': {}},
    OutputSerialization = {'JSON': {}},
)
 
 
for event in response['Payload']:
    if 'Records' in event:
        records = event['Records']['Payload'].decode('utf-8')
        print(records)
    elif 'Stats' in event:
        statsDetails = event['Stats']['Details']
        print("Stats details bytesScanned: ")
        print(statsDetails['BytesScanned'])
        print("Stats details bytesProcessed: ")
        print(statsDetails['BytesProcessed'])

8. athena create database

ath = boto3.client('athena')
 
# create database
ath.start_query_execution(
    QueryString='create database mytest',
    ResultConfiguration={'OutputLocation': s3_query_path})

9. athena create table(여기는 ddl file을 생성해서 진행, 경우에 따라서 직접 create query를 만들어줄 수 있음)

# create table
with open('./mydata.ddl') as ddl:
    ath.start_query_execution(
        QueryString=ddl.read(),
        ResultConfiguration={'OutputLocation': s3_query_path})
# mydata.ddl
CREATE EXTERNAL TABLE IF NOT EXISTS
mytest.mytable (
  col1 string,
  col2 integer
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION 's3://mytest/mytest/';

10. athena query 실행

#Function for starting athena query
def run_query(query, database, s3_output):
    client = boto3.client('athena')
    response = client.start_query_execution(
        QueryString=query,
        QueryExecutionContext={
            'Database': database
            },
        ResultConfiguration={
            'OutputLocation': s3_output,
            }
        )
    query_execution_id=response['QueryExecutionId']
 
    # get execution status
    for i in range(1, 1 + RETRY_COUNT):
        # get query execution
        query_status = client.get_query_execution(QueryExecutionId=query_execution_id)
        query_execution_status = query_status['QueryExecution']['Status']['State']
        if query_execution_status == 'SUCCEEDED':
            print("STATUS:" + query_execution_status)
            break
        if query_execution_status == 'FAILED':
            raise Exception("STATUS:" + query_execution_status)
        else:
            print("STATUS:" + query_execution_status)
            time.sleep(i)
    else:
        client.stop_query_execution(QueryExecutionId=query_execution_id)
        raise Exception('TIME OVER')
 
 
    # get query results
    result = client.get_query_results(QueryExecutionId=query_execution_id)
    print(result)
    return response

댓글()

docker로 mysql 5.7 설치하기

IT기술/cloud, docker|2021. 1. 15. 23:35

2019-12-18 작성

 

업무용 pc에 개발환경을 구축할 필요가 있어서 mysql을 설치하려고 보니,

docker가 쉬울 것 같아서 docker로 설치해본다. 아래와 같이 실행하면 root 비밀번호 없이 mysql이 설치된다.

docker run -d --name mysql -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=true mysql:5.7

-p는 대응할 port 옵션이다. [접속 원하는포트]:3306으로 입력하면 된다.
-e는 환경변수
마지막 mysql:5.7은 이미지 이름이다.
mysql db 파일을 로컬에 저장해두고 싶다면 아래와 같이 -v옵션을 사용할 수도 있다.
-v [로컬경로]:/var/lib/mysql

 

-e 옵션을 주지 않으면 다음과 같이 에러 메시지가 표시되는데, 원하는 비밀번호 형식에 따라서 -e 옵션을 바꿔줄 수 있다.

You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD

설치 후 mysql workbench를 통해서 접속할 수 있다.

댓글()

docker nginx로 http static file listing/download server 만들기

IT기술/cloud, docker|2021. 1. 15. 23:21

2019-12-05 작성

 

file download server가 필요할 때가 있다. 일시적으로 사용할 때는

다음과 같이 python(혹은 ruby, nodejs) 서버를 사용한다.

python -m SimpleHTTPServer
python3 -m http.server

하지만 file server를 유지해야할 때는 test서버를 쓰기가 좀 그렇다.(nohup 명령어를 사용해서 계속 사용할 수는 있다..)

 

그래서 여러가지 방안을 고민해봤는데(samba, linux repo 등), 용도가 http download라면 웹서버가 가장 쉬운 것 같다. 그래서 쉽게 docker nginx container를 사용하려고 하니 docker Nginx Official 페이지에 다음과 같이 simple static content를 위한 명령어가 설명돼 있다.

 

서버에서 아래와 같이 실행 하고 [/내경로]에 파일을 저장하면 "http://ip:port/파일명"으로 파일을 다운 받을 수 있게 된다. 그러면 다운로드 서버는 끝.

$ docker run --name nginx -v [/내경로]:/usr/share/nginx/html:ro -d -p [내포트]:80 nginx

 

그 다음, [/내경로]에 있는 파일 목록을 웹상에서 보고 싶다.
우선 docker nginx container에 접속해 vim을 설치한다.

$ docker exec -it [container_name] bash
$ apt-get update
$ apt-get upgrade
$ apt-get install vim

 

그 다음 nginx 설정 파일을 아래과 같이 수정한다.

vim /etc/nginx/nginx.conf

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    ###### 여기가 핵심
    server {
        location / {
            root /usr/share/nginx/html;
            autoindex on;
        }
    }
    ######

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

변경 후 nginx에 설정을 적용해준다.

$ nginx -t # 설정 테스트
$ nginx -s reload # 설정 반영

 

그러면 "http://ip:port/ "에서 file 목록을 확인할 수 있다. 만약 보안 문제로 목록을 보고 싶지 않다면 autoindex off로 변경한다.

 

참고사이트: https://blog.leocat.kr/notes/2018/01/08/nginx-simple-file-listing-server

'IT기술 > cloud, docker' 카테고리의 다른 글

AWS boto3 시작하기  (0) 2021.01.16
docker로 mysql 5.7 설치하기  (0) 2021.01.15

댓글()