Dimitri Tsiflitzis
7L International
Let's learn how to build and host our very first backend application using Vapor 4.
Releases | ||
---|---|---|
Version | Release date | Swift version |
1.0 | Sep 15, 2016 | ≥ 3.0 |
2.0 | May 17, 2017 | ≥ 3.1 |
3.0 | May 4, 2018 | ≥ 4.1 |
4.0 | April 9, 2020 | ≥ 5.2 |
5.0 | TBD | ≥ TBD |
Kitura
# macOS
brew install vapor/tap/vapor
# linux
eval $(curl -sL https://apt.vapor.sh)
sudo apt-get update
sudo apt-get install vapor
vapor new myProject
cd myProject
// open xcode & run
import Vapor
let app = try Application(.detect())
defer { app.shutdown() }
app.get("hello") { req in
return "Hello, world."
}
try app.run()
Using system provided directories
func configure(_ app: Application) throws {
print(app.directory.workingDirectory)
print(app.directory.publicDirectory)
print(app.directory.resourcesDirectory)
print(app.directory.viewsDirectory)
//...
}
You can pass your secrets to a Vapor application by using environment variables. .env files! 🎉
func configure(_ app: Application) throws {
let variable = Environment.get("EXAMPLE") ?? "undefined"
print(variable)
print(app.environment.name)
print(app.environment.arguments)
print(app.environment.commandInput)
if app.environment.isRelease {
print("production mode")
}
//...
}
Change port number and hostname
func configure(_ app: Application) throws {
app.http.server.configuration.hostname = "127.0.0.1"
app.http.server.configuration.port = 8081
//...
}
Router parameters
app.get("hello", ":world") { req -> String in
let param = req.parameters.get("world") ?? "default"
return "Hello, \(param.capitalized)!"
}
E.g. On AWS
The generated project will also include both a Dockerfile and a docker-compose.yml file
# Build image
FROM vapor/swift:5.2 as build
WORKDIR /build
COPY ./Package.* ./
RUN swift package resolve
COPY . .
RUN swift build --enable-test-discovery -c release -Xswiftc -g
# Run image
FROM vapor/ubuntu:18.04
WORKDIR /run
COPY --from=build /build/.build/release /run
COPY --from=build /usr/lib/swift/ /usr/lib/swift/
COPY --from=build /build/Public /run/Public
ENTRYPOINT ["./Run"]
CMD ["serve", "--env", "production", "--hostname", "0.0.0.0"]
The Dockerfile separates the build and run process into two distinct images. 🐋
docker build -t vapor-image .
# simply run the container instance & bind the port
docker run --name vapor-server -p 8080:8080 vapor-image
# run the instance, bind the port, see logs remove after exit (CTRL+C)
docker run --rm -p 8080:8080 -it vapor-image