'Cloud&Container'에 해당되는 글 30건

  1. 2020.07.13 [AWS] DescribeInstanceTypes from Java
  2. 2020.04.08 [Docker] Docker Compose TZ 설정
  3. 2020.04.01 [Docker] Docker Compose 로 Ubuntu 올리기
  4. 2020.03.31 [Docker] Ubuntu 에 Docker & Docker Compose 설치 하기
  5. 2020.03.31 [Docker] Amazon Linux 에 Docker & Compose 설치 하기.
  6. 2020.03.30 [Docker] Docker Compose 에서 volume 사용 하기
  7. 2020.03.30 [Docker] Image 다운로드 및 로컬 설치 하기
  8. 2020.03.27 [Docker] Docker Registry 구성 키워드
  9. 2020.03.26 [AWS] Spring Cloud Config S3 Backend 사용하기
  10. 2020.03.23 [AWS] IGW vs NAT GW

[AWS] DescribeInstanceTypes from Java

Cloud&Container/AWS 2020. 7. 13. 18:06

본 API 가 삭제 되었기 때문에 그냥 아래와 같이 단순하게 구성해 보았습니다.

 

@Service
@Log4j2
@RequiredArgsConstructor
public class Ec2Service {

  public ResponseEntity<String> describeInstanceTypes() {
    ProcessBuilder builder = new ProcessBuilder();
    String instances = "{}";

    try {
      builder.command("bash", "-c", "aws ec2 describe-instance-types");
      Process process = builder.start();

      instances = new BufferedReader(
        new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)).lines()
        .collect(Collectors.joining("\n"));

      int exitCode = process.waitFor();

      JSONObject jsonObject = new JSONObject(instances);
      JSONArray jsonArray = jsonObject.getJSONArray("InstanceTypes");
      JSONArray sortedJsonArray = new JSONArray();
      List list = new ArrayList();

      for(int i = 0; i < jsonArray.length(); i++) {
        list.add(jsonArray.getJSONObject(i));
      }

      Collections.sort(list, new Comparator<JSONObject>() {

        @Override
        public int compare(JSONObject a, JSONObject b) {
          String source = new String();
          String target = new String();

          try {
            source = (String)a.get("InstanceType");
            target = (String)b.get("InstanceType");
          } catch(Exception e) {
          }

          return source.compareTo(target);
        }
      });

      for(int i = 0; i < jsonArray.length(); i++) {
        sortedJsonArray.put(list.get(i));
      }

      instances = "{\"InstanceTypes\": " +sortedJsonArray.toString()+ "}";
    } catch(Exception e) {
      e.printStackTrace();
    }

    return ResponseEntity.ok(instances);
  }
}

 

코드 자체는 AWS CLI 를 ProcessBuilder 를 이용해서 외부 파일을 실행 시켜 데이터를 받아와서 처리 하는 내용입니다.

AWS CLI 로 데이터를 가져 오게 되면 정렬이 안된 상태로 데이터가 넘어 와서 별도 sort 기능 구현이 필요 합니다.

그냥 CLI 에서도 JSON Sort 옵션 하나 넣어 주면 좋았을 걸 아쉽더라고요.

 

근데 왜 이 API 를 없앴는지 차암....

 

1.x 에서 삭제 되어서 2.x 로 변경해서 사용 하시면 됩니다.

    Ec2Client ec2Client = Ec2Client.builder().build();
    DescribeInstanceTypesRequest request = DescribeInstanceTypesRequest.builder()
      .maxResults(100)
      .build();

    DescribeInstanceTypesResponse response = ec2Client.describeInstanceTypes(request);
    log.debug("{}", response.instanceTypes());

한번에 100개 씩 밖에 못 가져 오기 때문에 nextToken 으로 끝까지 요청 하셔야 합니다.

:

[Docker] Docker Compose TZ 설정

Cloud&Container/IaC 2020. 4. 8. 09:14

docker-compose tz 설정

 

Case 1)

volumes:
  - "/etc/localtime:/etc/localtime:ro"
  - "/etc/timezone:/etc/timezone:ro"


Case 2)

environment:
  - TZ=Asia/Seoul

 

:

[Docker] Docker Compose 로 Ubuntu 올리기

Cloud&Container/IaC 2020. 4. 1. 20:41

docker-compose.yml)

version: '3.7'
services:
  ubuntu-mac:
    image: ubuntu:18.04
    container_name: ubuntu-mac
    stdin_open: true
    tty: true
    command: [/bin/bash]

or

$ docker run --rm --name ubuntu-mac -ti ubuntu:18.04 /bin/bash

 

:

[Docker] Ubuntu 에 Docker & Docker Compose 설치 하기

Cloud&Container 2020. 3. 31. 15:59

ubuntu 18.04 에 docker & docker compose 설치)

 

# ubuntu user 로 설치
# https://docs.docker.com/install/linux/docker-ce/ubuntu/
$ sudo apt-get remove docker docker-engine docker.io containerd runc
$ sudo apt-get update
$ sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
OK
$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
$ sudo apt-get update
$ sudo apt-get install docker-ce docker-ce-cli containerd.io
$ apt-cache madison docker-ce
5:19.03.8~3-0~ubuntu-bionic

$ sudo apt-get install docker-ce=5:19.03.8~3-0~ubuntu-bionic docker-ce-cli=5:19.03.8~3-0~ubuntu-bionic containerd.io
$ sudo docker run hello-world

# https://docs.docker.com/compose/install/
# https://github.com/docker/compose 에서 latest version 을 확인 합니다.
$ sudo curl -L "https://github.com/docker/compose/releases/download/1.25.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
$ sudo chmod +x /usr/local/bin/docker-compose
$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
$ docker-compose --version

$ docker-compose up
ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.
$ sudo usermod -aG docker ubuntu
$ newgrp docker
:

[Docker] Amazon Linux 에 Docker & Compose 설치 하기.

Cloud&Container/IaC 2020. 3. 31. 14:06

Amazon linux docker & docker-compose 설치)

$ sudo yum update
$ sudo yum install docker
$ docker version
...중략...
Cannot connect to the Docker daemon at unix:///var/run/docker.sock.
Is the docker daemon running?
$ sudo service docker start
$ docker version
Got permission denied while trying to connect to the Docker daemon socket at 
unix:///var/run/docker.sock: 
Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/version: dial unix /var/run/docker.sock: 
connect: permission denied
$ sudo docker version
$ sudo usermod -a -G docker ec2-user

# https://github.com/docker/compose 에서 latest version 을 확인 합니다.
$ sudo curl -L https://github.com/docker/compose/releases/download/1.25.4/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
$ sudo chmod +x /usr/local/bin/docker-compose

$ docker-compose up
Couldn't connect to Docker daemon at http+docker://localhost - is it running?

$ sudo groupadd docker
$ sudo usermod -aG docker $USER
$ newgrp docker 

$ docker-compose up
:

[Docker] Docker Compose 에서 volume 사용 하기

Cloud&Container 2020. 3. 30. 14:40

기본 문서는 아래 링크 참고 하시면 됩니다.

 

Reference)

https://docs.docker.com/compose/compose-file/#volumes
https://docs.docker.com/compose/compose-file/#volume-configuration-reference

 

두 가지의 syntax 를 제공 하고 있습니다.

  1. Short Syntax
  2. Long Syntax

1. Short Syntax 

https://docs.docker.com/compose/compose-file/#short-syntax-3

valumes:
  - ${SOURCE-PATH}:${DESTINATION-PATH}:${MODE}

${SOURCE-PATH} 에는 Host의 Path 또는 Volume Name 을 사용 할 수 있습니다.

 

Case 1) bind mount 형식으로 volume 생성이 됩니다.

services:
...중략...
  volumes:
    - /mount/data:/usr/share/elasticsearch/mnt:rw
    
    
$ docker inspect ${SERVICE-NAME}
...중략...
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/mount/data",
                "Destination": "/usr/share/elasticsearch/mnt",
                "Mode": "rw",
                "RW": true,
                "Propagation": "rprivate"
            }
        ]
...중략...

 

Case 2) volume 형식으로 volume 생성이 됩니다.

- volume 사용 시 주의 사항은 Container 내부에 이미 생성 되어 있는 File System 을 사용

services:
...중략...
  volumes:
    - mount01:/usr/share/elasticsearch/data:rw
...중략...

volumes:
  mount01:
    driver: local      

$ docker volume ls --format "{{.Name}} : {{.Mountpoint}}"
megatoi-monitor-elasticsearch_mount01 : /var/lib/docker/volumes/megatoi-monitor-elasticsearch_mount01/_data

$ docker inspect ${SERVICE-NAME}
...중략...
        "Mounts": [
            {
                "Type": "volume",
                "Name": "megatoi-monitor-elasticsearch_mount01",
                "Source": "/var/lib/docker/volumes/megatoi-monitor-elasticsearch_mount01/_data",
                "Destination": "/usr/share/elasticsearch/data",
                "Driver": "local",
                "Mode": "rw",
                "RW": true,
                "Propagation": ""
            }
        ],
...중략...

 

2. Long Syntax

https://docs.docker.com/compose/compose-file/#long-syntax-3

기본 옵션만 살펴 보겠습니다.

자세한건 위 문서를 참고하세요.

  • type
    • volume
      • Volume 선언 시 Source 는 volumes: syntax 에서 named volume 선언이 되어 있어야 합니다.
    • bind
      • Source File System 이 만들어져 있어야 합니다.
  • source
    • Host File System  을 작성 합니다. 
    • Short Syntax 에서 처럼 Host 의 Path 또는 Volume Name 을 사용 할 수 있습니다.
  • target
    • Container File System 을 작성 합니다.

Case 1) bind mount 형식으로 volume 생성이 됩니다.

services:
...중략...
    volumes:
        - type: bind
          source: /mount/data
          target: /usr/share/elasticsearch/mnt
...중략...


$ docker inspect ${SERVICE-NAME}
...중략...
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/mount/data",
                "Destination": "/usr/share/elasticsearch/mnt",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
...중략...

 

Case 2) volume 형식으로 volume 생성이 됩니다.

- volume 사용 시 주의 사항은 Container 내부에 이미 생성 되어 있는 File System 을 사용

services:
...중략...
    volumes:
        - type: volume
          source: mount01
          target: /usr/share/elasticsearch/data
...중략...
volumes:
  mount01:
    driver: local
...중략...


$ docker inspect ${SERVICE-NAME}
...중략...
        "Mounts": [
            {
                "Type": "volume",
                "Name": "megatoi-monitor-elasticsearch_mount01",
                "Source": "/var/lib/docker/volumes/megatoi-monitor-elasticsearch_mount01/_data",
                "Destination": "/usr/share/elasticsearch/data",
                "Driver": "local",
                "Mode": "z",
                "RW": true,
                "Propagation": ""
            }
        ],
...중략...

hort Syntax 의 Case 2) 와 같이 사용도 가능 합니다.

:

[Docker] Image 다운로드 및 로컬 설치 하기

Cloud&Container/IaC 2020. 3. 30. 08:41

인터넷이 안되는 환경에서 설치를 해야 할 경우가 있을 수도 있어서 이미지를 다운로드 받아 설치 하는 명령어를 작성해 보았습니다.

찾아 보면 다 나와 있는 거라서 그냥 기억력을 돕는 차원에서 간단하게 작성 합니다.

 

- root 로 안할 경우 누락 되는 파일이 있을 수 있음.
- save : load
- export : import

 

로컬로 다운로드 받기)

$ sudo docker save [옵션] <파일명> [이미지명]
$ sudo docker save -o elasticsearch.tar docker.elastic.co/elasticsearch/elasticsearch:7.6.1

# docker-compose.yml 파일 안에 
# image: docker.elastic.co/elasticsearch/elasticsearch:7.6.1


이미지 올리기)

$ sudo docker load -i tar파일명
$ sudo docker load -i elasticsearch.tar


컨테이너 자체를 파일로 내리기)

$ sudo docker export <컨테이너명 or 컨테이너ID> > xxx.tar


컨테이너 올리기)

$ sudo docker import <파일 or URL> - [image name[:tag name]]

 

:

[Docker] Docker Registry 구성 키워드

Cloud&Container/IaC 2020. 3. 27. 10:50
  • Nexus3
  • Harbor
  • S3

 

참고문서)

https://velog.io/@king/%EC%82%AC%EB%82%B4-Docker-Registry-%EB%A7%8C%EB%93%A4%EA%B8%B0-Nexus3-%EA%B8%B0%EB%B0%98-e9k69evm4a

https://engineering.linecorp.com/ko/blog/harbor-for-private-docker-registry/

https://goharbor.io/

 

:

[AWS] Spring Cloud Config S3 Backend 사용하기

Cloud&Container/AWS 2020. 3. 26. 10:57

Spring Cloud Config Server 설정)

 

[S3 설정]
- S3 버킷 생성
- 접근권한 부여

[ConfigApplication.java]

@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {
  public static void main(String[] args) {
	SpringApplication.run(ConfigApplication.class, args);
  }
}


[build.gradle]

compile 'com.amazonaws:aws-java-sdk-s3'


[application.yml]

server:
port: 8888

spring:
  profiles:
    active: awss3
  cloud:
    config:
      server:
        awss3:
          region: ap-northeast-2
          bucket: s3config


[Config Server 접근 URL]

http://localhost:8888/${S3-FILE-NAME}/${PROFILE-NAME}

- 생성한 버킷 하위로 설정 파일 목록이 존재 해야 합니다.
- ${S3-FILE-NAME} 는 생성한 Bucket 아래 만든 설정 파일명 입니다.
- backoffice
- ${PROFILE-NAME} 은 설정 파일에 대한 프로필명 입니다.
- app1, app2

예제)
Config Server URL : 
http://localhost:8888/backoffice/app1

S3 :
megatoidiscons3config/backoffice-app1.yml
or
megatoidiscons3config/backoffice-app1.properties


[backoffice-app1.yml]

project.app1="backoffice-app1"


[backoffice-app2.yml]

project.app2="backoffice-app2"

 

Spring Cloud Config Client 설정)

[application.yml]

spring:
  cloud:
    config:
      name: backoffice
      uri: http://localhost:8888
      profile: app1,app2


[HelloController.java]

@RestController
public class HelloController {

  @Value ("${project.app1}")
  String projectApp1;

  @Value ("${project.app2}")
  String projectApp2;

  @RequestMapping("/app1")
  public String helloApp1() {
    return projectApp1;
  }

  @RequestMapping("/app2")
  public String helloApp2() {
    return projectApp2;
  }
}

 

git 사용 하는 건 문서들이 많이 나와 있어서 s3 로 정리해 봤습니다.

:

[AWS] IGW vs NAT GW

Cloud&Container/AWS 2020. 3. 23. 10:43

VPC 를 구성 하면서 외부 통신을 위해서는 IGW 가 꼭 필요 합니다.

만약 외부 통신이 필요 하지 않은 VPC 라면 IGW 를 구성 하지 않아도 되겠죠.

 

NAT GW 는 VPC 구성 후 Private Subnet 에 있는 리소스가 외부와 Internet 통신을 하기 위해 필요한 서비스 입니다.

이 과정에서 Elastic IP 가 필요 합니다.

 

이 두 GW 의 차이점이 더 궁금하신 분은 아래 문서 참고 하세요.

 

https://medium.com/awesome-cloud/aws-vpc-difference-between-internet-gateway-and-nat-gateway-c9177e710af6

Internet Gateway

An Internet Gateway (IGW) is a logical connection between an Amazon VPC and the Internet. It is not a physical device. Only one can be associated with each VPC. It does not limit the bandwidth of Internet connectivity. (The only limitation on bandwidth is the size of the Amazon EC2 instance, and it applies to all traffic — internal to the VPC and out to the Internet.)

If a VPC does not have an Internet Gateway, then the resources in the VPC cannot be accessed from the Internet (unless the traffic flows via a corporate network and VPN/Direct Connect).

An Internet Gateway allows resources within your VPC to access the internet, and vice versa. In order for this to happen, there needs to be a routing table entry allowing a subnet to access the IGW.

That is to say — an IGW allows resources within your public subnet to access the internet, and the internet to access said resources.

A subnet is deemed to be a Public Subnet if it has a Route Table that directs traffic to the Internet Gateway.


NAT Gateway

A NAT Gateway does something similar, but with two main differences:

  1. It allows resources in a private subnet to access the internet (think yum updates, external database connections, wget calls, OS patch, etc)
  2. It only works one way. The internet at large cannot get through your NAT to your private resources unless you explicitly allow it.

AWS introduced a NAT Gateway Service that can take the place of a NAT Instance. The benefits of using a NAT Gateway service are:

  • It is a fully-managed service — just create it and it works automatically, including fail-over
  • It can burst up to 10 Gbps (a NAT Instance is limited to the bandwidth associated with the EC2 instance type)

However:

  • Security Groups cannot be associated with a NAT Gateway
  • You’ll need one in each AZ since they only operate in a single AZ
: