1652509440
Chào mọi người. Trong hướng dẫn từng bước này, tôi muốn chỉ cho bạn cách triển khai Kotlin Microservice bằng Docker và AWS App Runner.
Chúng ta sẽ cùng nhau tìm hiểu:
Tôi biết, nó có vẻ như là một khối lượng công việc lớn. Nhưng tôi tin rằng bạn sẽ thấy nó có thể đơn giản như thế nào với ngăn xếp công nghệ ở trên.
Trước khi bắt đầu, hãy đảm bảo rằng bạn đã cài đặt Docker trên máy cục bộ của mình. Chúng tôi sẽ cần phải chứa ứng dụng của mình.
Nếu bạn không có Docker, thì tài liệu Docker chính thức sẽ giúp bạn thiết lập nó trong vài phút.
Trước tiên, hãy dành vài phút để hiểu chính xác AWS App Runner là gì.
Nói một cách đơn giản, đây là một dịch vụ được quản lý hoàn toàn cho phép bạn xây dựng và triển khai các ứng dụng web và API được chứa trong vùng một cách dễ dàng.
Nó xử lý rất nhiều thứ, như cân bằng tải lưu lượng truy cập hoặc mở rộng quy mô, giúp các nhà phát triển như bạn và tôi tập trung vào mã.
AWS App Runner đôi khi là một lựa chọn tuyệt vời khi tạo bản demo hoặc bằng chứng về khái niệm, nhưng nó cũng đáng xem xét đối với các nhóm nhỏ hơn mà không có người chuyên dụng làm việc trên cơ sở hạ tầng.
Như đã nói, hãy chuẩn bị một API REST đơn giản bằng cách sử dụng Kotlin và Ktor.
Nếu bạn không quan tâm đến việc triển khai Ktor, thì bạn có thể chỉ cần sao chép kho lưu trữ GitHub này và chuyển sang bước Cách tạo hình ảnh Docker .
Nếu bạn đang sử dụng IntelliJ IDEA Ultimate Edition, thì bạn có thể tạo dự án Ktor bằng ứng dụng. Nếu không, bạn có thể sử dụng công cụ Ktor Project Generator và tải dự án xuống máy cục bộ của mình.
Bất kể lựa chọn của bạn là gì, hãy đảm bảo nhập các plugin sau:
Sau khi bạn đã nhập dự án, hãy tạo Serialization.kt
tệp và đăng ký application/json
loại nội dung cho tính năng Thương lượng nội dung:
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
}
Nói một cách đơn giản, với đoạn mã này, chúng ta sẽ có thể tuần tự hóa các đối tượng Kotlin thành JSON (và giải mã hóa JSON thành các đối tượng).
Bây giờ hãy triển khai một MessageDto
lớp dữ liệu như sau:
@Serializable
data class MessageDto(val message: String)
Về cơ bản, chúng tôi sẽ sử dụng lớp chung này để cung cấp thông điệp cho người tiêu dùng API của chúng tôi.
Bước tiếp theo, hãy tạo một Routing.kt
tệp và hiển thị một điểm cuối mới:
fun Application.configureRouting() {
routing {
helloWorldRoute()
}
}
fun Routing.helloWorldRoute() {
route("/hello") {
get {
call.respond(HttpStatusCode.OK, MessageDto("Hello World!"))
}
}
}
Như bạn có thể thấy, ứng dụng của chúng tôi sẽ phản hồi với mã trạng thái 200 OK cho mỗi GET
yêu cầu đến /hello
đường dẫn.
Bây giờ, hãy kết hợp mọi thứ bên trong Application.kt
tệp:
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureRouting()
configureSerialization()
}.start(wait = true)
}
Như bạn có thể thấy, microservice Kotlin của chúng tôi sẽ là một máy chủ nhúng Netty đang chạy trên đó localhost:8080
.
Tôi thực sự khuyến khích bạn chạy ứng dụng và xác minh rằng mọi thứ đang hoạt động bình thường:
GET localhost:8080/hello
Status: 200 OK
Response Body:
{
"message": "Hello World!"
}
Cuối cùng, hãy thêm Dockerfile
vào thư mục gốc của dự án của chúng tôi:
FROM openjdk:8-jdk
EXPOSE 8080:8080
RUN mkdir /app
COPY ./build/install/com.codersee.ktor-app-runner/ /app/
WORKDIR /app/bin
CMD ["./com.codersee.ktor-app-runner"]
Đảm bảo rằng thư mục được chỉ định cho các lệnh COPY
và CMD
khớp với giá trị của rootProject.name
bên trong settings.gradle.kts
tệp. Nếu tên của dự án là xyz
, thì các lệnh này sẽ phản ánh rằng:
...
COPY ./build/install/xyz/ /app/
...
CMD ["./xyz"]
Tại thời điểm này, chúng tôi có mọi thứ cần thiết để xây dựng Hình ảnh Docker của mình, mà chúng tôi sẽ sử dụng sau này cho việc triển khai AWS App Runner .
Bước đầu tiên, hãy chạy installDist
lệnh với Gradle Wrapper:
./gradlew installDist
Lệnh trên có nhiệm vụ tập hợp nội dung phân phối và cài đặt nó trên máy hiện tại. Mặc dù nghe có vẻ khó khăn nhưng nó chỉ đơn giản là tạo các tệp cần thiết bên trong thư mục ./build/install/{project-name}/
.
Bước tiếp theo, hãy xây dựng Hình ảnh Docker:
docker build -t ktor-aws-runner .
Như bạn có thể thấy, chúng tôi đã đặt tên cho hình ảnh mong muốn của mình ktor-aws-runner
bằng -t
tùy chọn (một phím tắt cho --tag
).
Cuối cùng, hãy chạy vùng chứa của chúng tôi để đảm bảo rằng microservice Kotlin của chúng tôi đang hoạt động bình thường:
docker run -p 8080:8080 ktor-aws-runner
Như một lời giải thích, -p
flag ( --port
) chịu trách nhiệm xuất bản cảng của container 8080
tới cảng chủ 8080
.
Sau khi hoàn tất, sau vài giây, chúng ta sẽ thấy thông báo sau trong nhật ký:
Application started in 0.078 seconds
Tương tự, chúng ta có thể thực hiện yêu cầu GET để kiểm tra xem điểm cuối tiếp xúc có phản hồi chính xác hay không.
Với tất cả những điều đó đã được thực hiện, cuối cùng chúng tôi cũng có thể bắt đầu làm việc với AWS. Nhưng trước khi có thể đẩy Docker Image của mình, chúng ta cần đảm bảo rằng chúng ta đã cài đặt AWS CLI trên máy cục bộ của mình.
Chúng ta có thể làm điều đó một cách dễ dàng với lệnh dưới đây:
aws --version
# Result:
aws-cli/2.5.3 Python/3.9.11 Windows/10 exe/AMD64 prompt/off
Kết quả trên cho thấy rằng mọi thứ đã được thiết lập chính xác. Tuy nhiên, nếu chúng tôi muốn cài đặt hoặc cập nhật CLI, thì AWS sẽ gửi một bài viết thực sự tốt về vấn đề đó trong tài liệu chính thức của họ .
Ngoài ra, chúng tôi phải có quyền truy cập vào Đám mây AWS từ máy tính của mình - và đó là những gì chúng tôi sẽ thiết lập trong bước này.
Để thiết lập quyền truy cập, hãy đăng nhập vào Bảng điều khiển quản lý AWS và điều hướng đến tính năng Người dùng của Bảng điều khiển IAM . Chúng tôi có thể làm điều đó một cách dễ dàng với thanh tìm kiếm ở trên cùng:
Trên trang tiếp theo, hãy nhấp vào nút Thêm người dùng :
Sau đó, chúng tôi sẽ chỉ định Tên người dùng ưa thích cùng với khóa Truy cập - Loại thông tin xác thực truy cập có lập trình :
Với những cài đặt này, chúng tôi sẽ có thể truy cập AWS bằng cách sử dụng kết hợp khóa truy cập và bí mật.
Sau khi hoàn tất, hãy nhấn nút Tiếp theo . Trên trang này, chúng tôi phải chọn nhóm cho người dùng của chúng tôi. Với mục đích của hướng dẫn này, hãy tạo một cái mới, bằng cách sử dụng nút hiển thị bên dưới:
Tiếp theo, hãy chỉ định tên Nhóm ( admin-group
trong trường hợp của tôi) trong phương thức và chọn AdministratorAccess :
Để đơn giản, chúng ta sẽ sử dụng AdministratorAccess. Nhưng trong các tình huống thực tế, chúng ta nên luôn tuân thủ Nguyên tắc Ít Đặc quyền.
Sau khi nhóm được tạo, hãy nhấn nút Tiếp theo một lần nữa:
Trên trang tiếp theo, chúng tôi có tùy chọn thêm thẻ tùy chỉnh dưới dạng cặp khóa-giá trị.
Nhưng chúng ta sẽ không cần chúng hôm nay, vì vậy chúng ta chỉ cần bỏ qua trang này:
Cuối cùng, chúng tôi sẽ được chuyển hướng đến trang Xem lại , nơi chúng tôi có thể xác thực các bước trước đó của mình:
Như bạn có thể thấy, mọi thứ đều ổn, vì vậy hãy nhấp vào Tạo người dùng :
Người dùng đã được tạo thành công, vì vậy cuối cùng chúng tôi có thể nhập khóa truy cập và khóa bí mật của mình.
Hãy nhớ rằng khóa truy cập và khóa bí mật là những dữ liệu có tính bảo mật cao và bạn không bao giờ được chia sẻ chúng với bất kỳ ai!
Hãy nhấp vào nút Tải xuống .csv và tìm nạp tệp. Cá nhân tôi đã đặt tên cho nó some_user_credentials.csv
, nhưng hãy chọn bất kỳ tên nào bạn thích (và ghi nhớ nó :)).
Tiếp theo, hãy điều hướng đến thư mục tải xuống và chạy lệnh sau:
aws configure import --csv file://some_user_credentials.csv
# Result:
Successfully imported 1 profile(s)
Với thông báo trên, chúng ta có thể mong đợi rằng mọi thứ đã được thiết lập chính xác. Ngoài ra, chúng tôi có thể xác minh rằng một tệp mới được gọi là credentials
đã được tạo (hoặc cập nhật) bên trong thư mục .aws
.
Nếu bạn đang sử dụng Windows thì đường dẫn của bạn sẽ là C:\Users\[your_user_name]\.aws
:
[some-admin]
aws_access_key_id = [your access key id]
aws_secret_access_key = [your secret]
Tại thời điểm này, CLI của chúng tôi đã được chuẩn bị đúng cách, vì vậy chúng tôi có thể học cách đẩy Hình ảnh Docker cục bộ của chúng tôi vào Cơ quan đăng ký vùng chứa đàn hồi .
Bước đầu tiên, hãy quay lại Bảng điều khiển quản lý và nhập sổ đăng ký vùng chứa vào thanh tìm kiếm:
Hãy nhấp vào Đăng ký vùng chứa đàn hồi và trên trang tiếp theo, nút Tạo kho lưu trữ . Trên trang tiếp theo, hãy chọn một kho lưu trữ Riêng tư và chỉ định tên cho nó:
Đối với phần còn lại của cài đặt, hãy để các giá trị mặc định, giống như bên dưới:
Cuối cùng, hãy nhấn nút Tạo kho lưu trữ .
Sau đó, chúng tôi sẽ được chuyển hướng đến danh sách Kho lưu trữ riêng, hiện chứa kho lưu trữ mới được tạo của chúng tôi:
Hãy sao chép URI và chỉ định lệnh sau trong thiết bị đầu cuối trên máy cục bộ của chúng tôi:
docker tag ktor-aws-runner:latest [your_registry_uri]:latest
# Example: docker tag ktor-aws-runner:latest 111111111111.dkr.ecr.us-east-1.amazonaws.com/my-ktor-registry:latest
Tại sao chúng ta cần điều đó? Về cơ bản, khi làm việc với Docker , chúng ta cần gắn thẻ hình ảnh với máy chủ đăng ký và cổng (nếu cần) để đẩy chúng vào bất kỳ kho lưu trữ riêng tư nào.
Sau khi hoàn tất, hãy xác thực với sổ đăng ký Amazon ECR:
aws ecr get-login-password --profile some-admin --region us-east-1 | docker login --username AWS --password-stdin [your registry URI]
# Result:
Login Succeeded
Sau đó, chúng ta có thể chạy git push
lệnh để đẩy hình ảnh sang ECR:
docker push [your_tagged_image]
# Example: docker push 111111111111.dkr.ecr.us-east-1.amazonaws.com/my-ktor-registry:latest
Tùy thuộc vào kết nối của bạn, có thể mất một chút thời gian, nhưng cuối cùng, chúng ta sẽ thấy danh sách cập nhật trong kho lưu trữ của chúng tôi:
Bây giờ chúng tôi có mọi thứ chúng tôi cần để chia sẻ microservice Kotlin của chúng tôi với thế giới :)
Hãy quay lại Bảng điều khiển quản lý và tìm kiếm người chạy ứng dụng:
Trên trang tiếp theo, hãy nhấn nút Tạo dịch vụ .
Đối với cấu hình Nguồn, hãy chọn sổ đăng ký Vùng chứa cùng với Amazon ECR :
Như bạn có thể nhận thấy, AWS App Runner có thể triển khai các dịch vụ trực tiếp từ kho mã nguồn. Nếu bạn quan tâm đến cấu hình như vậy, chỉ cần liên hệ với tôi qua email (liên hệ với [at] codersee [dot] com).
Tiếp theo, hãy nhấp vào Duyệt và chọn hình ảnh đã tạo trước đó :
Hãy nhấp vào tiếp tục và đối với cài đặt Triển khai, hãy chọn Thủ công và Tạo vai trò dịch vụ mới:
Tên vai trò không quan trọng trong hướng dẫn này, vì vậy chúng tôi có thể chỉ định bất kỳ giá trị nào.
Bước tiếp theo, hãy nhấp vào Tiếp theo và trên trang tiếp theo, hãy cung cấp tên Dịch vụ cùng với thông tin CPU , Bộ nhớ và Cổng :
Hình ảnh trình bày Tên dịch vụ, cpu, bộ nhớ, các biến môi trường, cổng và cài đặt cấu hình bổ sung
Như bạn có thể thấy, chúng tôi đã chọn kết hợp khả dụng tối thiểu (và đó là điều tôi khuyên bạn nên làm).
Nếu chúng tôi muốn chỉ định một số biến môi trường bổ sung hoặc lệnh Bắt đầu tùy chỉnh, thì trang này cho phép chúng tôi làm như vậy. Nhưng chúng tôi sẽ không cần bất kỳ biến môi trường nào và chúng tôi đã thêm lệnh bắt đầu vào Docker Image của chúng tôi, vì vậy hãy để nguyên như vậy.
Trên trang Tự động điều chỉnh tỷ lệ, chọn Cấu hình tùy chỉnh :
Tiếp theo, hãy tạo một cấu hình mới có tên là cấu hình của tôi :
Như tôi đã đề cập ở phần đầu, AWS App Runner xử lý rất nhiều thứ. Một trong số đó là tính năng tự động mở rộng quy mô. Mặc dù đó là một tính năng tuyệt vời, chúng tôi phải giới hạn nó theo sở thích của mình và luôn nhớ rằng nhiều tài nguyên hơn đồng nghĩa với chi phí cao hơn.
Như bạn có thể thấy ở trên, cấu hình ví dụ này sẽ không mở rộng Kotlin Microservice của chúng tôi . Tuy nhiên, nếu chúng tôi tăng kích thước Tối đa, thì một phiên bản mới sẽ được tạo mỗi khi số lượng yêu cầu đồng thời tăng lên 10.
Hãy thêm cấu hình ở trên và để mặc định phần còn lại của các mục. Sau khi chúng tôi nhấp vào Tiếp theo, chúng tôi sẽ thấy trang Đánh giá với tóm tắt triển khai.
Trên trang này, hãy nhấp vào Create and Deploy
nút, nút này sẽ bắt đầu quá trình triển khai:
Và một lần nữa, quá trình này có thể mất vài phút. Sau khi kết thúc, trạng thái sẽ thay đổi từ Operation in progress
thành Running
và chúng tôi sẽ có thể kiểm tra API Ktor REST của mình.
Giống như trước đây, hãy kiểm tra GET /hello
điểm cuối. Nhưng lần này, với tư cách là tên máy chủ của microservice của chúng tôi, chúng tôi cần sử dụng giá trị từ Default domain
:
#Example:
GET https://aaaaaaaaaa.us-east-1.awsapprunner.com/hello
Status: 200 OK
Response Body:
{
"message": "Hello World!"
}
Hãy nhớ xóa tất cả các tài nguyên chúng tôi đã tạo hôm nay để bạn không bị tính phí cho chúng.
Thực sự rất dễ quên tất cả những thứ chúng tôi tạo ra khi học AWS Cloud và tại một số điểm, bạn có thể vượt quá hạn ngạch miễn phí của mình. Vì vậy, nó là một thực hành tốt để loại bỏ tất cả những điều đó.
Và đó là tất cả cho hướng dẫn này về cách triển khai Kotlin Microservice lên Đám mây AWS với AWS App Runner. Tôi thực sự hy vọng rằng sau khi làm theo hướng dẫn này, bạn có thể dễ dàng triển khai các ứng dụng của mình lên Amazon Cloud.
Nguồn: https://www.freecodecamp.org/news/kotlin-aws-app-runner/
1651140677
Micro — Asynchronous HTTP microservices
async
and await
Important: Micro is only meant to be used in production. In development, you should use micro-dev, which provides you with a tool belt specifically tailored for developing microservices.
To prepare your microservice for running in the production environment, firstly install micro
:
npm install --save micro
Create an index.js
file and export a function that accepts the standard http.IncomingMessage and http.ServerResponse objects:
module.exports = (req, res) => {
res.end('Welcome to Micro')
}
Micro provides useful helpers but also handles return values – so you can write it even shorter!
module.exports = () => 'Welcome to Micro'
Next, ensure that the main
property inside package.json
points to your microservice (which is inside index.js
in this example case) and add a start
script:
{
"main": "index.js",
"scripts": {
"start": "micro"
}
}
Once all of that is done, the server can be started like this:
npm start
And go to this URL: http://localhost:3000
- 🎉
micro - Asynchronous HTTP microservices
USAGE
$ micro --help
$ micro --version
$ micro [-l listen_uri [-l ...]] [entry_point.js]
By default micro will listen on 0.0.0.0:3000 and will look first
for the "main" property in package.json and subsequently for index.js
as the default entry_point.
Specifying a single --listen argument will overwrite the default, not supplement it.
OPTIONS
--help shows this help message
-v, --version displays the current version of micro
-l, --listen listen_uri specify a URI endpoint on which to listen (see below) -
more than one may be specified to listen in multiple places
ENDPOINTS
Listen endpoints (specified by the --listen or -l options above) instruct micro
to listen on one or more interfaces/ports, UNIX domain sockets, or Windows named pipes.
For TCP (traditional host/port) endpoints:
$ micro -l tcp://hostname:1234
For UNIX domain socket endpoints:
$ micro -l unix:/path/to/socket.sock
For Windows named pipe endpoints:
$ micro -l pipe:\\.\pipe\PipeName
async
& await
Examples
Micro is built for usage with async/await.
const sleep = require('then-sleep')
module.exports = async (req, res) => {
await sleep(500)
return 'Ready!'
}
When you want to set the port using an environment variable you can use:
micro -l tcp://0.0.0.0:$PORT
Optionally you can add a default if it suits your use case:
micro -l tcp://0.0.0.0:${PORT-3000}
${PORT-3000}
will allow a fallback to port 3000
when $PORT
is not defined.
Note that this only works in Bash.
Examples
For parsing the incoming request body we included an async functions buffer
, text
and json
const {buffer, text, json} = require('micro')
module.exports = async (req, res) => {
const buf = await buffer(req)
console.log(buf)
// <Buffer 7b 22 70 72 69 63 65 22 3a 20 39 2e 39 39 7d>
const txt = await text(req)
console.log(txt)
// '{"price": 9.99}'
const js = await json(req)
console.log(js.price)
// 9.99
return ''
}
buffer(req, { limit = '1mb', encoding = 'utf8' })
text(req, { limit = '1mb', encoding = 'utf8' })
json(req, { limit = '1mb', encoding = 'utf8' })
async
function that can be run with await
.limit
is how much data is aggregated before parsing at max. Otherwise, an Error
is thrown with statusCode
set to 413
(see Error Handling). It can be a Number
of bytes or a string like '1mb'
.Error
is thrown with statusCode
set to 400
(see Error Handling)For other types of data check the examples
So far we have used return
to send data to the client. return 'Hello World'
is the equivalent of send(res, 200, 'Hello World')
.
const {send} = require('micro')
module.exports = async (req, res) => {
const statusCode = 400
const data = { error: 'Custom error message' }
send(res, statusCode, data)
}
send(res, statusCode, data = null)
require('micro').send
.statusCode
is a Number
with the HTTP status code, and must always be supplied.data
is supplied it is sent in the response. Different input types are processed appropriately, and Content-Type
and Content-Length
are automatically set.Stream
: data
is piped as an octet-stream
. Note: it is your responsibility to handle the error
event in this case (usually, simply logging the error and aborting the response is enough).Buffer
: data
is written as an octet-stream
.object
: data
is serialized as JSON.string
: data
is written as-is.400
error is thrown. See Error Handling.You can use Micro programmatically by requiring Micro directly:
const http = require('http')
const micro = require('micro')
const sleep = require('then-sleep')
const server = new http.Server(micro(async (req, res) => {
await sleep(500)
return 'Hello world'
}))
server.listen(3000)
micro(fn)
default
export.require('micro')
.(req, res) => void
signature. That uses the provided function
as the request handler.await
. So it can be async
sendError(req, res, error)
require('micro').sendError
.error.statusCode
.error.message
as the body.console.error
and during development (when NODE_ENV
is set to 'development'
) also sent in responses.throw
.createError(code, msg, orig)
require('micro').createError
.statusCode
.orig
sets error.originalError
which identifies the original error (if any).Micro allows you to write robust microservices. This is accomplished primarily by bringing sanity back to error handling and avoiding callback soup.
If an error is thrown and not caught by you, the response will automatically be 500
. Important: Error stacks will be printed as console.error
and during development mode (if the env variable NODE_ENV
is 'development'
), they will also be included in the responses.
If the Error
object that's thrown contains a statusCode
property, that's used as the HTTP code to be sent. Let's say you want to write a rate limiting module:
const rateLimit = require('my-rate-limit')
module.exports = async (req, res) => {
await rateLimit(req)
// ... your code
}
If the API endpoint is abused, it can throw an error with createError
like so:
if (tooMany) {
throw createError(429, 'Rate limit exceeded')
}
Alternatively you can create the Error
object yourself
if (tooMany) {
const err = new Error('Rate limit exceeded')
err.statusCode = 429
throw err
}
The nice thing about this model is that the statusCode
is merely a suggestion. The user can override it:
try {
await rateLimit(req)
} catch (err) {
if (429 == err.statusCode) {
// perhaps send 500 instead?
send(res, 500)
}
}
If the error is based on another error that Micro caught, like a JSON.parse
exception, then originalError
will point to it. If a generic error is caught, the status will be set to 500
.
In order to set up your own error handling mechanism, you can use composition in your handler:
const {send} = require('micro')
const handleErrors = fn => async (req, res) => {
try {
return await fn(req, res)
} catch (err) {
console.log(err.stack)
send(res, 500, 'My custom error!')
}
}
module.exports = handleErrors(async (req, res) => {
throw new Error('What happened here?')
})
Micro makes tests compact and a pleasure to read and write. We recommend ava, a highly parallel Micro test framework with built-in support for async tests:
const http = require('http')
const micro = require('micro')
const test = require('ava')
const listen = require('test-listen')
const fetch = require('node-fetch')
test('my endpoint', async t => {
const service = new http.Server(micro(async (req, res) => {
micro.send(res, 200, {
test: 'woot'
})
}))
const url = await listen(service)
const response = await fetch(url)
const body = await response.json()
t.deepEqual(body.test, 'woot')
service.close()
})
Look at test-listen for a function that returns a URL with an ephemeral port every time it's called.
npm link
npm link micro
. Instead of the default one from npm, node will now use your clone of Micro!As always, you can run the AVA and ESLint tests using: npm test
Thanks to Tom Yandell and Richard Hodgson for donating the name "micro" on npm!
Disclaimer: Micro was created for use within containers and is not intended for use in serverless environments. For those using Vercel, this means that there is no requirement to use Micro in your projects as the benefits it provides are not applicable to the platform. Utility features provided by Micro, such as json
, are readily available in the form of Serverless Function helpers.
This readme is the documentation for the canary
(prerelease) branch. To view the documentation for the latest stable Micro version visit npmjs.com/micro.
Author: Vercel
Source Code: https://github.com/vercel/micro
License: MIT License
1650263879
Hello, everyone. In this step-by-step tutorial, I would like to show you how to deploy a Kotlin Microservice using Docker and AWS App Runner.
Together, we will learn:
I know, it might sound like a tremendous amount of work. But I am convinced that you will find out how simple it can be with the above tech stack.
Before we start, make sure that you have Docker already installed on you local machine. We'll need to containerize our application.
If you don't have Docker, then the official Docker documentation will help you set it up in a few minutes.
First, let's take minute to understand what exactly AWS App Runner is.
To put it simply, it is a fully managed service which allows you to build and deploy containerized web applications and APIs with ease.
It takes care of plenty of things, like traffic load balancing, or scaling, which helps developers like you and me focus on the code.
AWS App Runner oftentimes is a great choice when creating a demo or proof of concept, but it's also worth considering for smaller teams without a dedicated person working on infrastructure.
With that being said, let's prepare a simple REST API using Kotlin and Ktor.
If you are not interested in the Ktor implementation, then you can simply clone this GitHub repository and proceed to the How to Build the Docker Image step.
If you are using the IntelliJ IDEA Ultimate Edition, then you can create a Ktor project using the app. Otherwise, you can use the Ktor Project Generator tool and download project to your local machine.
Regardless of your choice, make sure to import the following plugins:
After you've imported the project, create the Serialization.kt
file and register application/json
content type to the ContentNegotiation feature:
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
}
In simple words, with this code snippet we will be able to serialize Kotlin objects into JSON (and deserialize the JSON into objects, as well).
Now let's implement a MessageDto
data class like this:
@Serializable
data class MessageDto(val message: String)
Basically, we will use this generic class to provide messages for our API consumers.
As the next step, let's create a Routing.kt
file and expose a new endpoint:
fun Application.configureRouting() {
routing {
helloWorldRoute()
}
}
fun Routing.helloWorldRoute() {
route("/hello") {
get {
call.respond(HttpStatusCode.OK, MessageDto("Hello World!"))
}
}
}
As you can see, our application will respond with a 200 OK status code to each GET
request to the /hello
path.
Now, let's combine everything inside the Application.kt
file:
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureRouting()
configureSerialization()
}.start(wait = true)
}
As you can see, our Kotlin microservice will be a Netty embedded server running on localhost:8080
.
I highly encourage you to run the application and verify that everything is working properly:
GET localhost:8080/hello
Status: 200 OK
Response Body:
{
"message": "Hello World!"
}
Finally, let's add the Dockerfile
to the root directory of our project:
FROM openjdk:8-jdk
EXPOSE 8080:8080
RUN mkdir /app
COPY ./build/install/com.codersee.ktor-app-runner/ /app/
WORKDIR /app/bin
CMD ["./com.codersee.ktor-app-runner"]
Make sure that the directory specified for the COPY
and CMD
commands matches the value of rootProject.name
inside the settings.gradle.kts
file. If the project's name is xyz
, then these commands should reflect that:
...
COPY ./build/install/xyz/ /app/
...
CMD ["./xyz"]
At this point, we have everything we need to build our Docker Image, which we will use later for the AWS App Runner deployment.
As the first step, let's run the installDist
command with Gradle Wrapper:
./gradlew installDist
The above command is responsible for assembling the distribution content and installing it on the current machine. Although it might sound difficult, it will simply create necessary files inside the ./build/install/{project-name}/
directory.
As the next step, let's build a Docker Image:
docker build -t ktor-aws-runner .
As you can see, we named our desired image ktor-aws-runner
with the -t
option (a shortcut for --tag
).
Finally, let's run our container to make sure that our Kotlin microservice is working properly:
docker run -p 8080:8080 ktor-aws-runner
As a word of explanation, the -p
flag (--port
) is responsible for publishing the container's 8080
port to the host 8080
port.
With that being done, after a few seconds we should see the following message in logs:
Application started in 0.078 seconds
Similarly, we can perform a GET request to check if the exposed endpoint is responding correctly.
With all of that being done, we can finally start working with AWS. But before we're able to push our Docker Image, we need to make sure that we have AWS CLI installed on our local machine.
We can do that easily with the below command:
aws --version
# Result:
aws-cli/2.5.3 Python/3.9.11 Windows/10 exe/AMD64 prompt/off
The above result indicates that everything is setup correctly. Nevertheless, if we would like to install or update the CLI, then AWS ships with a really good article on that in their official documentation.
Additionally, we have to have the access to AWS Cloud from our computer – and that's what we are going to set up in this step.
In order to set up the access, let's sign in to the AWS Management Console and navigate to the Users feature of the IAM Console. We can do that easily with the search bar at the top:
On the next page, let's click the Add users button:
Then we'll specify the preferred User name along with the Access key – Programmatic access credential type:
With these settings, we will be able to access AWS using a combination of access key and secret.
With that being done, let's hit the Next button. On this page, we have to select the group for our user. For the purpose of this tutorial, let's create a new one, using the button visible below:
Nextly, let's specify a Group name ( admin-group
in my case) in the modal and select the AdministratorAccess:
For simplicity, we are going to use the AdministratorAccess. But in real-life scenarios, we should always stick to The Principle of Least Privilege.
After the group is created, let's hit the Next button once again:
On the next page, we have the option of adding custom tags as key-value pairs.
But we won't need them today, so let's simply skip this page:
Finally, we will be redirected to the Review page, where we can validate our previous steps:
As you can see, everything looks good, so let's click Create user:
The user was created successfully, so we can finally import our access and secret keys.
Keep in mind that access and secret keys are highly confidential data and you should never share them with anyone!
Let's click the Download .csv button and fetch the file. Personally, I named it some_user_credentials.csv
, but feel free to pick whatever name you like (and remember it :) ).
Next, let's navigate to the download directory and run the following command:
aws configure import --csv file://some_user_credentials.csv
# Result:
Successfully imported 1 profile(s)
Given the above message, we can expect that everything was set up correctly. Additionally, we can verify that a new file called credentials
has been created (or updated) inside the .aws
directory.
If you are using Windows then your path will be C:\Users\[your_user_name]\.aws
:
[some-admin]
aws_access_key_id = [your access key id]
aws_secret_access_key = [your secret]
At this point, our CLI is properly prepared, so we can learn how to push our local Docker Image to the Elastic Container Registry.
As the first step, let's get back to the Management Console and type container registry in the search bar:
Let's click on the Elastic Container Registry and on the next page, the Create repository button. On the next page, let's select a Private repository and specify a name for it:
For the rest of settings, let's leave the default values, just like below:
Finally, let's hit the Create repository button.
After that, we will be redirected to the Private repositories list, which now contains our newly created repository:
Let's copy the URI and specify the following command in the terminal on our local machine:
docker tag ktor-aws-runner:latest [your_registry_uri]:latest
# Example: docker tag ktor-aws-runner:latest 111111111111.dkr.ecr.us-east-1.amazonaws.com/my-ktor-registry:latest
Why do we need that? Well, basically, when working with Docker we need to tag images with registry host and port (if necessary) in order to push them to any private repository.
With that being done, let's authenticate to the Amazon ECR registry:
aws ecr get-login-password --profile some-admin --region us-east-1 | docker login --username AWS --password-stdin [your registry URI]
# Result:
Login Succeeded
After that, we can run the git push
command in order to push the image to ECR:
docker push [your_tagged_image]
# Example: docker push 111111111111.dkr.ecr.us-east-1.amazonaws.com/my-ktor-registry:latest
Depending on your connection it can take some time, but finally, we should see the update list in our repository:
Now we have everything we need to share our Kotlin microservice with the world :)
Let's get back to the Management Console and search for app runner:
On the next page, let's hit the Create service button.
For the Source configuration, let's choose the Container registry along with Amazon ECR:
As you might have noticed, AWS App Runner can deploy services directly from a source code repository. If you are interested in such a configuration, just get in touch with me via email (contact[at]codersee[dot]com).
Next, let's click Browse and select previously created image:
Let's click continue and for the Deployment settings let's choose Manual and Create new service role:
The role name is not important in this tutorial, so we can specify any value.
As the next step, let's click Next and on the next page, let's provide a Service name along with CPU, Memory and Port information:
Image presents Service name, cpu, memory, environment variables, port and additional configuration settings
As you can see, we have chosen the minimum available combination (and that's what I suggest you do as well).
If we would like to specify some additional environment variables or a custom Start command, then this page allows us to do so. But we won't need any environment variables and we have already added a start command to our Docker Image, so let's leave it as it is.
On the Auto scaling page, select the Custom configuration:
Next, let's create a new configuration called my-configuration:
As I have mentioned in the beginning, AWS App Runner takes care of plenty of things out of the box. One of them is auto scaling. Although it is a great feature, we have to limit it to our preferences and always remember that more resources means higher costs.
As you can see above, this example configuration will not scale our Kotlin Microservice. However, if we increase the Maximum size, then a new instance will be created each time the number of simultaneous request increases by 10.
Let's add the above config and leave the rest of items with their defaults. After we click Next, we will see the Review page with deployment summary.
On this page, let's click Create and Deploy
button, which will start the deployment process:
And again, this process can take a few minutes. After it finishes, the status will change from Operation in progress
to Running
and we will be able to test our Ktor REST API.
Just like previously, let's test the GET /hello
endpoint. But this time, as a host name of our microservice, we need to use the value from Default domain
:
#Example:
GET https://aaaaaaaaaa.us-east-1.awsapprunner.com/hello
Status: 200 OK
Response Body:
{
"message": "Hello World!"
}
Please remember to delete all the resources we've created today, so that you won't be charged for them.
It's really easy to forget about all the things we create when learning AWS Cloud and at some point, you may exceed your free quota. Thus, it is a good practice to remove all of that.
And that's all for this tutorial on how to deploy Kotlin Microservice to AWS Cloud with AWS App Runner. I really hope that after following along with this guide, you're able to easily deploy your applications to Amazon Cloud.
Original article source at https://www.freecodecamp.org
#kotlin #microservice #aws #cloud #docker
1650254653
Bonjour à tous. Dans ce didacticiel pas à pas, je voudrais vous montrer comment déployer un microservice Kotlin à l'aide de Docker et d'AWS App Runner.
Ensemble, nous apprendrons :
Je sais, cela peut sembler être une énorme quantité de travail. Mais je suis convaincu que vous découvrirez à quel point cela peut être simple avec la pile technologique ci-dessus.
Avant de commencer, assurez-vous que Docker est déjà installé sur votre machine locale. Nous devrons conteneuriser notre application.
Si vous n'avez pas Docker, la documentation officielle de Docker vous aidera à le configurer en quelques minutes.
Tout d'abord, prenons quelques minutes pour comprendre ce qu'est exactement AWS App Runner .
Pour le dire simplement, il s'agit d'un service entièrement géré qui vous permet de créer et de déployer facilement des applications Web et des API conteneurisées.
Il prend en charge de nombreuses choses, comme l'équilibrage de la charge du trafic ou la mise à l'échelle, ce qui aide les développeurs comme vous et moi à se concentrer sur le code.
AWS App Runner est souvent un excellent choix lors de la création d'une démonstration ou d'une preuve de concept, mais cela vaut également la peine d'être envisagé pour les petites équipes sans personne dédiée travaillant sur l'infrastructure.
Cela étant dit, préparons une API REST simple en utilisant Kotlin et Ktor.
Si vous n'êtes pas intéressé par l'implémentation de Ktor, vous pouvez simplement cloner ce référentiel GitHub et passer à l' étape Comment créer l'image Docker .
Si vous utilisez IntelliJ IDEA Ultimate Edition, vous pouvez créer un projet Ktor à l'aide de l'application. Sinon, vous pouvez utiliser l' outil Ktor Project Generator et télécharger le projet sur votre ordinateur local.
Quel que soit votre choix, assurez-vous d'importer les plugins suivants :
Après avoir importé le projet, créez le Serialization.kt
fichier et enregistrez application/json
le type de contenu dans la fonctionnalité ContentNegotiation :
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
}
En termes simples, avec cet extrait de code, nous pourrons sérialiser des objets Kotlin en JSON (et désérialiser également le JSON en objets).
Implémentons maintenant une MessageDto
classe de données comme celle-ci :
@Serializable
data class MessageDto(val message: String)
Fondamentalement, nous utiliserons cette classe générique pour fournir des messages à nos consommateurs d'API.
À l'étape suivante, créons un Routing.kt
fichier et exposons un nouveau point de terminaison :
fun Application.configureRouting() {
routing {
helloWorldRoute()
}
}
fun Routing.helloWorldRoute() {
route("/hello") {
get {
call.respond(HttpStatusCode.OK, MessageDto("Hello World!"))
}
}
}
Comme vous pouvez le voir, notre application répondra avec un code d'état 200 OKGET
à chaque demande au /hello
chemin.
Maintenant, combinons tout à l'intérieur du Application.kt
fichier :
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureRouting()
configureSerialization()
}.start(wait = true)
}
Comme vous pouvez le voir, notre microservice Kotlin sera un serveur embarqué Netty fonctionnant sur localhost:8080
.
Je vous encourage vivement à lancer l'application et à vérifier que tout fonctionne correctement :
GET localhost:8080/hello
Status: 200 OK
Response Body:
{
"message": "Hello World!"
}
Enfin, ajoutons le Dockerfile
au répertoire racine de notre projet :
FROM openjdk:8-jdk
EXPOSE 8080:8080
RUN mkdir /app
COPY ./build/install/com.codersee.ktor-app-runner/ /app/
WORKDIR /app/bin
CMD ["./com.codersee.ktor-app-runner"]
Assurez-vous que le répertoire spécifié pour les commandes COPY
et CMD
correspond à la valeur de rootProject.name
dans le settings.gradle.kts
fichier. Si le nom du projet est xyz
, ces commandes doivent refléter cela :
...
COPY ./build/install/xyz/ /app/
...
CMD ["./xyz"]
À ce stade, nous avons tout ce dont nous avons besoin pour créer notre Docker Image , que nous utiliserons plus tard pour le déploiement d' AWS App Runner .
Dans un premier temps, exécutons la installDist
commande avec Gradle Wrapper :
./gradlew installDist
La commande ci-dessus est responsable de l'assemblage du contenu de la distribution et de son installation sur la machine actuelle. Bien que cela puisse sembler difficile, cela créera simplement les fichiers nécessaires dans le ./build/install/{project-name}/
répertoire.
À l'étape suivante, construisons une image Docker :
docker build -t ktor-aws-runner .
Comme vous pouvez le voir, nous avons nommé notre image souhaitée ktor-aws-runner
avec l' -t
option (un raccourci pour --tag
).
Enfin, exécutons notre conteneur pour nous assurer que notre microservice Kotlin fonctionne correctement :
docker run -p 8080:8080 ktor-aws-runner
En guise d'explication, le -p
drapeau ( --port
) est responsable de la publication du port du conteneur sur le 8080
port hôte 8080
.
Cela étant fait, après quelques secondes, nous devrions voir le message suivant dans les journaux :
Application started in 0.078 seconds
De même, nous pouvons effectuer une requête GET pour vérifier si le point de terminaison exposé répond correctement.
Avec tout cela fait, nous pouvons enfin commencer à travailler avec AWS. Mais avant de pouvoir pousser notre image Docker, nous devons nous assurer que l' AWS CLI est installée sur notre machine locale.
Nous pouvons le faire facilement avec la commande ci-dessous :
aws --version
# Result:
aws-cli/2.5.3 Python/3.9.11 Windows/10 exe/AMD64 prompt/off
Le résultat ci-dessus indique que tout est configuré correctement. Néanmoins, si nous souhaitons installer ou mettre à jour la CLI, alors AWS est livré avec un très bon article à ce sujet dans leur documentation officielle .
De plus, nous devons avoir accès à AWS Cloud depuis notre ordinateur - et c'est ce que nous allons configurer dans cette étape.
Afin de configurer l'accès, connectons-nous à AWS Management Console et naviguons jusqu'à la fonction Utilisateurs de la console IAM . Nous pouvons le faire facilement avec la barre de recherche en haut :
Sur la page suivante, cliquons sur le bouton Ajouter des utilisateurs :
Ensuite, nous spécifierons le nom d'utilisateur préféré avec la clé d'accès - type d'informations d'identification d'accès programmatique :
Avec ces paramètres, nous pourrons accéder à AWS en utilisant une combinaison de clé d'accès et de secret.
Ceci étant fait, cliquons sur le bouton Suivant. Sur cette page, nous devons sélectionner le groupe pour notre utilisateur. Pour les besoins de ce tutoriel, créons-en un nouveau, en utilisant le bouton visible ci-dessous :
Ensuite, spécifions un nom de groupe ( admin-group
dans mon cas) dans le modal et sélectionnons AdministratorAccess :
Pour plus de simplicité, nous allons utiliser l'AdministratorAccess. Mais dans des scénarios réels, nous devons toujours nous en tenir au principe du moindre privilège.
Une fois le groupe créé, cliquons à nouveau sur le bouton Suivant :
Sur la page suivante, nous avons la possibilité d'ajouter des balises personnalisées en tant que paires clé-valeur.
Mais nous n'en aurons pas besoin aujourd'hui, alors sautons simplement cette page :
Enfin, nous serons redirigés vers la page Review , où nous pourrons valider nos étapes précédentes :
Comme vous pouvez le voir, tout semble bon, alors cliquons sur Créer un utilisateur :
L'utilisateur a été créé avec succès, nous pouvons donc enfin importer nos clés d'accès et secrètes.
Gardez à l'esprit que les clés d'accès et secrètes sont des données hautement confidentielles et que vous ne devez jamais les partager avec qui que ce soit !
Cliquons sur le bouton Télécharger .csv et récupérons le fichier. Personnellement, je l'ai nommé some_user_credentials.csv
, mais n'hésitez pas à choisir le nom que vous aimez (et souvenez-vous-en :) ).
Ensuite, naviguons jusqu'au répertoire de téléchargement et exécutons la commande suivante :
aws configure import --csv file://some_user_credentials.csv
# Result:
Successfully imported 1 profile(s)
Compte tenu du message ci-dessus, nous pouvons nous attendre à ce que tout soit correctement configuré. De plus, nous pouvons vérifier qu'un nouveau fichier appelé credentials
a été créé (ou mis à jour) dans le .aws
répertoire.
Si vous utilisez Windows alors votre chemin sera C:\Users\[your_user_name]\.aws
:
[some-admin]
aws_access_key_id = [your access key id]
aws_secret_access_key = [your secret]
À ce stade, notre CLI est correctement préparée, nous pouvons donc apprendre à pousser notre image Docker locale vers Elastic Container Registry .
Dans un premier temps, revenons à la console de gestion et saisissez registre de conteneurs dans la barre de recherche :
Cliquons sur Elastic Container Registry et sur la page suivante, le bouton Create repository . Sur la page suivante, sélectionnons un dépôt privé et spécifions-lui un nom :
Pour le reste des paramètres, laissons les valeurs par défaut, comme ci-dessous :
Enfin, cliquons sur le bouton Créer un référentiel .
Après cela, nous serons redirigés vers la liste des référentiels privés, qui contient désormais notre référentiel nouvellement créé :
Copions l'URI et spécifions la commande suivante dans le terminal sur notre machine locale :
docker tag ktor-aws-runner:latest [your_registry_uri]:latest
# Example: docker tag ktor-aws-runner:latest 111111111111.dkr.ecr.us-east-1.amazonaws.com/my-ktor-registry:latest
Pourquoi avons-nous besoin de cela? Eh bien, en gros, lorsque nous travaillons avec Docker, nous devons baliser les images avec l'hôte et le port de registre (si nécessaire) afin de les pousser vers n'importe quel référentiel privé.
Cela étant fait, authentifions-nous auprès du registre Amazon ECR :
aws ecr get-login-password --profile some-admin --region us-east-1 | docker login --username AWS --password-stdin [your registry URI]
# Result:
Login Succeeded
Après cela, nous pouvons exécuter la git push
commande afin de pousser l'image vers ECR :
docker push [your_tagged_image]
# Example: docker push 111111111111.dkr.ecr.us-east-1.amazonaws.com/my-ktor-registry:latest
Selon votre connexion, cela peut prendre un certain temps, mais finalement, nous devrions voir la liste des mises à jour dans notre référentiel :
Nous avons maintenant tout ce dont nous avons besoin pour partager notre microservice Kotlin avec le monde :)
Revenons à la console de gestion et recherchons l'exécuteur d'application :
Sur la page suivante, cliquons sur le bouton Créer un service .
Pour la configuration Source, choisissons le registre Container avec Amazon ECR :
Comme vous l'avez peut-être remarqué, AWS App Runner peut déployer des services directement à partir d'un référentiel de code source. Si vous êtes intéressé par une telle configuration, contactez-moi simplement par e-mail (contact[at]codersee[dot]com).
Ensuite, cliquons sur Parcourir et sélectionnons l'image créée précédemment :
Cliquons sur Continuer et pour les paramètres de déploiement, choisissons Manuel et Créer un nouveau rôle de service :
Le nom du rôle n'est pas important dans ce didacticiel, nous pouvons donc spécifier n'importe quelle valeur.
À l'étape suivante, cliquons sur Suivant et sur la page suivante, fournissons un nom de service ainsi que des informations sur le processeur , la mémoire et le port :
L'image présente le nom du service, le processeur, la mémoire, les variables d'environnement, le port et les paramètres de configuration supplémentaires
Comme vous pouvez le voir, nous avons choisi la combinaison minimale disponible (et c'est ce que je vous suggère de faire également).
Si nous souhaitons spécifier des variables d'environnement supplémentaires ou une commande de démarrage personnalisée, cette page nous permet de le faire. Mais nous n'aurons besoin d'aucune variable d'environnement et nous avons déjà ajouté une commande de démarrage à notre image Docker, alors laissons-la telle quelle.
Sur la page Auto scaling, sélectionnez la configuration personnalisée :
Ensuite, créons une nouvelle configuration appelée my-configuration :
Comme je l'ai mentionné au début, AWS App Runner s'occupe de beaucoup de choses prêtes à l'emploi. L'un d'eux est la mise à l'échelle automatique. Bien qu'il s'agisse d'une fonctionnalité intéressante, nous devons la limiter à nos préférences et toujours nous rappeler que plus de ressources signifient des coûts plus élevés.
Comme vous pouvez le voir ci-dessus, cet exemple de configuration ne fera pas évoluer notre microservice Kotlin . Cependant, si nous augmentons la taille maximale, une nouvelle instance sera créée à chaque fois que le nombre de requêtes simultanées augmente de 10.
Ajoutons la configuration ci-dessus et laissons le reste des éléments avec leurs valeurs par défaut. Après avoir cliqué sur Suivant, nous verrons la page de révision avec le résumé du déploiement.
Sur cette page, cliquons sur le Create and Deploy
bouton qui lancera le processus de déploiement :
Et encore une fois, ce processus peut prendre quelques minutes. Une fois terminé, le statut passera de Operation in progress
à Running
et nous pourrons tester notre API REST Ktor.
Comme précédemment, testons le point de GET /hello
terminaison. Mais cette fois, en tant que nom d'hôte de notre microservice, nous devons utiliser la valeur de Default domain
:
#Example:
GET https://aaaaaaaaaa.us-east-1.awsapprunner.com/hello
Status: 200 OK
Response Body:
{
"message": "Hello World!"
}
N'oubliez pas de supprimer toutes les ressources que nous avons créées aujourd'hui , afin qu'elles ne vous soient pas facturées.
Il est vraiment facile d'oublier tout ce que nous créons lors de l'apprentissage d'AWS Cloud et à un moment donné, vous pouvez dépasser votre quota gratuit. Il est donc recommandé de supprimer tout cela.
Et c'est tout pour ce didacticiel sur le déploiement du microservice Kotlin sur le cloud AWS avec AWS App Runner. J'espère vraiment qu'après avoir suivi ce guide, vous pourrez facilement déployer vos applications sur Amazon Cloud.
Si vous avez apprécié ce matériel, vous voudrez peut-être consulter mes autres articles . Sur mon blog, je couvre de nombreux sujets liés à Kotlin, Ktor et Spring Boot.
Link: https://www.freecodecamp.org/news/kotlin-aws-app-runner/
1647091980
OPS
Ops is a tool for creating and running a Nanos unikernel. It is used to package, create and run your application as a nanos unikernel instance.
Check out the DOCS
Installation
Most users should just download the binary from the website:
curl https://ops.city/get.sh -sSfL | sh
Building from source is easy if you have used Go before.
This program requires GO Version 1.13.x or greater.
Installing from source follows these general steps:
Install dependencies:
make deps
Build:
make build
macOS notes:
GO111MODULE=on go build -ldflags "-w"
For detailed instructions please consult the documentation.
Basic usage examples
Before learning more about ops
it is a good idea to see some basic usage examples. Below are links to simple examples using various programming platforms:
Let's run your first unikernel right now.
Throw this into hi.js:
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(8083, "0.0.0.0");
console.log('Server running at http://127.0.0.1:8083/');
Then you can run it like so:
ops pkg load node_v11.5.0 -p 8083 -f -n -a hi.js
Want to push your app out to the cloud?
For Google: https://nanovms.gitbook.io/ops/google_cloud
For AWS: https://nanovms.gitbook.io/ops/aws
Languages:
Various langauge examples can be found at https://github.com/nanovms/ops-examples.
Applications:
You can always find more pre-made packages via:
ops pkg list
The Apple M1 and M2 are ARM based. OPS is built for users primarily deploying to x86 based servers. While you can certainly run ARM builds with Nanos and OPS be aware that if you are trying to run x86 builds (the default) on ARM based M1s you won't be able to use hardware acceleration.
Build a bootable image
ops build <app>
Package and run
ops run <app>
# or
ops run -p <port> <app>
Using a config file
ops run -p <port> -c <file> <app>
Example config file
ops config files are plain JSON, below is an example
{
"Args":["one","two"],
"Dirs":["myapp/static"]
}
New users wishing to play around in a dev environment are encouraged to use the default user-mode networking. Other production users are encouraged to utilize native cloud builds such as Google Cloud which handle networking for you.
Only advanced/power users should use the bridge networking option.
Feel free to open up a pull request. It's helpful to have your OPS version and the release channel you are using.
Also - if it doesn't work on the main release you can try the nightly - the main release can tail the nightly by many weeks sometimes.
ops version
if you are using a package, get the package hash:
jq '."gnatsd_1.4.1"' ~/.ops/packages/manifest.json
If you have an idea for a new feature and it might take longer than a few hours or days to do it's worth opening a feature request tkt to ideate it first before jumping into code. There might be someone already working on the feature or plans to do something entirely different.
Feel free to email security at.
If you are having trouble running a particular application please feel free to open an issue and we can take a look. In general we'll only want to support the latest release from a given application/project, however, if you really want/need support for something older there are paid support plans available - contact the folks at https://nanovms.com.
Author: Nanovms
Source Code: https://github.com/nanovms/ops
License: MIT License
1644812364
Cube.js is an open-source analytical API platform. It is primarily used to build internal business intelligence tools or add customer-facing analytics to existing applications.
Cube.js was designed to work with serverless data warehouses and query engines like Google BigQuery and AWS Athena. A multi-stage querying approach makes it suitable for handling trillions of data points. Most modern RDBMS work with Cube.js as well and can be further tuned for performance.
For more details, see the Cube.js introduction page in our documentation.
If you are building your own business intelligence tool or customer-facing analytics most probably you'll face the following problems:
Cube.js has necessary infrastructure for every analytic application that heavily relies on its caching and pre-aggregation layer to provide several minutes raw data to insight delay and sub second API response times on a trillion of data points scale.
There're two ways to create a Cube.js application.
If you have Node.js installed, run this command and follow with the Getting Started guide.
$ npx cubejs-cli create hello-world
In case you don't have Node.js, or you'd like to run Cube.js with Docker, have a look at the Getting started with Docker guide.
If you have any questions or need help - please join our Slack community of amazing developers and contributors.
You are also welcome to join our monthly community calls where we discuss community news, Cube Dev team's plans, backlogs, use cases, etc. If you miss the call, the recordings will also be available after the meeting.
There are many ways you can contribute and help Cube.js. Here a few ones:
All sort of contributions are welcome and extremely helpful 🙌 Please refer to the contribution guide for more information.
Download Details:
Author: cube-js
Source Code: https://github.com/cube-js/cube.js
#nodejs #javascript #mysql #rust #chart #sql #spark #microservice #serverless #postgresql #cube
1642126525
Microservice applications are composed of small, independently versioned, and scalable customer-focused services that communicate over standard protocols with well-defined interfaces. This session will explore the Microservices architecture, and we will write our first microservice with .NET and Docker.
#microservice #docker #aspnetcore #aspnetcore
1641264600
El artículo explica uno de los patrones transversales en la arquitectura de microservicios conocido como patrón de disyuntor. La arquitectura de microservicio es una arquitectura distribuida que comprende algunos de los componentes distribuidos como Kafka. La arquitectura puede ser de naturaleza poliglótica. Puede haber cualquier cantidad de servicios en la arquitectura que depende del tipo de problema que se esté resolviendo, es importante que cuando los servicios se comunican entre sí todos los servicios deben estar activos, en el artículo vamos a entender
Un disyuntor es un dispositivo cuya finalidad es proteger los circuitos eléctricos de daños en caso de cortocircuitos o sobrecargas, detiene el flujo de electricidad en caso de un defecto para proteger los electrodomésticos y prevenir el riesgo de incendio. De manera similar, el patrón de diseño del interruptor automático deja de enviar la solicitud al servicio que no está funcionando o tarda demasiado en responder, el patrón salva a la arquitectura de eventos tan desastrosos y ayuda a construir sistemas resistentes y tolerantes a fallas.
El disyuntor se encuentra entre el mecanismo de solicitud y respuesta como un proxy, cuando el microservicio experimenta fallas o lentitud, el disyuntor se dispara durante una duración determinada, en ese período la solicitud a un servicio en particular fallará inmediatamente. Una vez finalizada la duración, el disyuntor permitirá algunas solicitudes al servicio y mantendrá el servicio en observación y si los servicios responden correctamente, el disyuntor reanuda el flujo como antes, si hay fallas en el servicio, el disyuntor permanece disparado hasta que se resuelva el problema.
El patrón del disyuntor tiene tres estados
El estado CERRADO es el Escenario Happy Path, el flujo está funcionando normalmente, los Microservicios están en funcionamiento, en este estado el Circuito permite las solicitudes a través del servicio.
Cuando los tiempos de espera del disyuntor alcanzan un valor configurado al llamar al microservicio, lo que significa que el microservicio tiene lentitud o no funciona como se esperaba, el disyuntor se dispara y pasa a un estado ABIERTO. Cuando el circuito está en estado ABIERTO, las solicitudes entrantes se devolverán con un error y no se ejecutarán llamadas de microservicio. Este comportamiento reduce aún más la carga y permite que el microservicio se recupere de la falla.
Después de un tiempo, el circuito pasa al estado HALF-OPEN. En el estado HALF-OPEN, Circuit realiza una solicitud de prueba al Servicio periódicamente para probar si el servicio se recupera de la falla o no. Si las llamadas de servicio aún se agota el tiempo de espera, el circuito permanece en el estado ABIERTO, si las llamadas son exitosas, el circuito cambia a un estado CERRADO y el tráfico continuará como de costumbre.
Es un patrón muy importante y útil para los microservicios que hace que la arquitectura del microservicio sea tolerante a fallas, como hemos visto, este patrón maneja los tiempos de espera, lentitud de manera efectiva que ayuda en la recuperación oportuna de los microservicios. Hay varias bibliotecas de código abierto de Circuit Breaker disponibles, algunas de las cuales son ampliamente utilizadas son, Hystrix, Resilience4j.
Enlace: https://www.c-sharpcorner.com/article/microservice-circuit-breaker-pattern/
1641253560
この記事では、サーキットブレーカーパターンと呼ばれるマイクロサービスアーキテクチャのクロスカッティングパターンの1つについて説明します。マイクロサービスアーキテクチャは、Kafkaなどの分散コンポーネントの一部を含む分散アーキテクチャであり、アーキテクチャは本質的に多言語である可能性があります。解決されている問題の種類に応じて、アーキテクチャにはいくつものサービスが存在する可能性があります。サービスが相互に通信するときは、すべてのサービスが生きている必要があることが重要です。
サーキットブレーカは、短絡や過負荷の場合に電気回路を損傷から保護することを目的としたデバイスであり、機器を保護し、火災のリスクを防ぐために、欠陥が発生した場合に電気の流れを停止します。同様に、Circuit Breakerの設計パターンは、機能していない、または応答に時間がかかりすぎるサービスへの要求の送信を停止します。このパターンは、アーキテクチャをそのような悲惨なイベントから保護し、フォールトトレラントで復元力のあるシステムの構築に役立ちます。
サーキットブレーカーは、プロキシとして要求メカニズムと応答メカニズムの間に位置します。マイクロサービスで障害が発生したり、サーキットブレーカーが特定の期間トリップするのが遅くなったりすると、その期間中、特定のサービスへの要求はすぐに失敗します。期間が終了すると、Circuit Breakerはサービスへのいくつかの要求を許可し、サービスを監視下に置きます。サービスが正常に応答した場合、Circuit Breakerは以前と同じようにフローを再開し、サービスに障害が発生した場合、CircuitBreakerは残ります。問題が解決するまでトリップしました。
サーキットブレーカーパターンには3つの状態があります
CLOSED状態はハッピーパスシナリオであり、フローは正常に機能しており、マイクロサービスは稼働しています。この状態では、Circuitはサービスを介したリクエストを許可します。
サーキットブレーカーのタイムアウトがマイクロサービスの呼び出しで構成された値に達すると、マイクロサービスの速度が低下しているか、期待どおりに機能していないことを意味します。サーキットブレーカーがトリップしてOPEN状態になります。CircuitがOPEN状態の場合、着信要求はエラーとともに返され、マイクロサービス呼び出しは実行されません。この動作により、負荷がさらに軽減され、マイクロサービスが障害から回復できるようになります。
しばらくすると、CircuitはHALF-OPEN状態になります。HALF-OPEN状態では、Circuitは定期的にサービスに試行要求を行い、サービスが障害から回復したかどうかをテストします。それでもサービスコールがタイムアウトする場合、CircuitはOPEN状態のままです。コールが成功すると、CircuitはCLOSED状態に切り替わり、トラフィックは通常どおりに進みます。
これはマイクロサービスにとって非常に重要で有用なパターンであり、マイクロサービスアーキテクチャをフォールトトレラントにします。このパターンはタイムアウトと速度低下を効果的に処理し、マイクロサービスのタイムリーなリカバリに役立ちます。利用可能なさまざまなCircuitBreakerオープンソースライブラリがあり、広く使用されているもののいくつかは、Hystrix、Resilience4jです。
リンク:https://www.c-sharpcorner.com/article/microservice-circuit-breaker-pattern/
1640855484
Building microservice applications with .NET today isn't easy. You need to coordinate multiple application startup, handle service discovery, manage dependencies and secrets, learn how to set up and manage Kubernetes, and more. Project Tye is a developer tool that makes developing, testing, and deploying microservices and distributed applications easier. Project Tye includes a local orchestrator to make developing microservices easier and the ability to deploy microservices to Kubernetes with minimal configuration. Come get an overview of how Project Tye helps you to develop microservice applications, from initial project to deployment and management.
#dotnet #microservice
1639448493
Microservice applications are composed of small, independently versioned, and scalable customer-focused services that communicate with each other over standard protocols with well-defined interfaces. Each microservice typically encapsulates simple business logic, which you can scale out or in, test, deploy, and manage independently. Smaller teams develop a microservice based on a customer scenario and use any technologies that they want to use. This module will teach you how to build your first microservice with .NET. In this episode, you will:
- Explain what microservices are.
- Know how various technologies involved in microservices are and how they relate.
- Build a microservice using .NET.
#dotnet #microservice
1639237539
More than a buzzword, microservices are here to stay and are currently gaining popularity due to their acceptance in the systems development market. In this article, we’ll explore some valuable features available on the .NET platform and create our first microservice.
Results obtained recently show that the architecture based on microservices can be a great option when implementing new features.
1638323461
In this video we learn how to work with HTTP and build our first Python Micro service.
We learn how to get a development environment in docker, get our basic customer application running and cover the fundamentals of HTTP.
Source Code 🧐
--------------------------------------------------------------
https://github.com/marcel-dempers/docker-development-youtube-series
#python #docker #microservice
1636020900
In this video, we will understand seeding data via Entity Framework into SQL Server database for our ASP.NET Core 6.0 Minimal API microservice.
#entity-framework #entity #dotnet #api #microservice #sql-server
1630806155
Learn how to deploy an AI microservice REST API endpoint to extract text from images using FastAPI, pytesseract, Docker, & DigitalOcean App Platform.
0:00:00 Welcome
0:01:08 Requirements
00:03:01 Setup Environment
00:08:52 Your first FastAPI App
00:16:03 FastAPI & Jinja Templates
00:29:09 FastAPI & PyTest
00:36:30 FastAPI Git & pre-commit
00:45:34 Deploy to DigitalOcean
00:53:36 Deploy Docker App to DigitalOcean App Platform
01:17:19 FastAPI Settings & Environment Variables & dotenv
01:23:33 Handling File Uploads
01:32:33 Automated Testing File Uploads
01:41:58 Image Upload Validation & Tests
01:51:26 Implementing Tesseract & pytesseract
02:05:06 Authorization Headers
02:16:05 Production Endpoint & Authorization Tests
02:19:28 One-Click Deploy on DigitalOcean App Platform
02:27:01 Thank you
⦿ Code: https://github.com/codingforentrepreneurs/FastAPI-Microservice-for-Django
#python #ai #microservice #fastapi #docker #digitalocean