Make application dockerised

Update mail_app to also have different forms of configuration outside of a single base yaml file. Allows local or production configurations to be established.
This commit is contained in:
Nick Bland 2021-11-16 14:34:05 +10:00
parent 1f06f5e66f
commit c9e564d48f
No known key found for this signature in database
GPG Key ID: B46CF88E4DAB4A2C
11 changed files with 102 additions and 9 deletions

2
.Dockerignore Normal file
View File

@ -0,0 +1,2 @@
/target
.vscode

3
.gitignore vendored
View File

@ -1,2 +1,3 @@
/target /target
.vscode .vscode
.env

7
Cargo.lock generated
View File

@ -547,6 +547,9 @@ name = "either"
version = "1.6.1" version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
dependencies = [
"serde 1.0.130",
]
[[package]] [[package]]
name = "encoding_rs" name = "encoding_rs"
@ -1631,6 +1634,7 @@ version = "1.0.68"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f690853975602e1bfe1ccbf50504d67174e3bcf340f23b5ea9992e0587a52d8" checksum = "0f690853975602e1bfe1ccbf50504d67174e3bcf340f23b5ea9992e0587a52d8"
dependencies = [ dependencies = [
"indexmap",
"itoa", "itoa",
"ryu", "ryu",
"serde 1.0.130", "serde 1.0.130",
@ -1810,9 +1814,12 @@ dependencies = [
"dotenv", "dotenv",
"either", "either",
"heck", "heck",
"hex",
"once_cell", "once_cell",
"proc-macro2", "proc-macro2",
"quote", "quote",
"serde 1.0.130",
"serde_json",
"sha2", "sha2",
"sqlx-core", "sqlx-core",
"sqlx-rt", "sqlx-rt",

View File

@ -29,7 +29,8 @@ features = [
"postgres", "postgres",
"uuid", "uuid",
"chrono", "chrono",
"migrate" "migrate",
"offline"
] ]
[dev-dependencies] [dev-dependencies]

11
Dockerfile Normal file
View File

@ -0,0 +1,11 @@
FROM rust:1.56
WORKDIR /app
COPY . .
ENV SQLX_OFFLINE true
RUN CARGO BUILD --release
ENV APP_ENVIRONMENT production
ENTRYPOINT ["./target/release/mail_app"]

View File

@ -1,4 +1,5 @@
application_port: 8000 application:
port: 8000
database: database:
host: "localhost" host: "localhost"
port: 5432 port: 5432

2
configuration/local.yaml Normal file
View File

@ -0,0 +1,2 @@
application:
host: 127.0.0.1

View File

@ -0,0 +1,2 @@
application:
host: 0.0.0.0

18
sqlx-data.json Normal file
View File

@ -0,0 +1,18 @@
{
"db": "PostgreSQL",
"5db1f9dfcdee685b02851f144e29d3e2726127d5a1d614880a0be89d8fa6904b": {
"query": "\n INSERT INTO subscriptions (id, email, name, subscribed_at)\n VALUES($1, $2, $3, $4)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Text",
"Text",
"Timestamptz"
]
},
"nullable": []
}
}
}

View File

@ -1,7 +1,15 @@
use std::convert::{TryFrom, TryInto};
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct Settings { pub struct Settings {
pub database: DatabaseSettings, pub database: DatabaseSettings,
pub application_port: u16 pub application: ApplicationSettings,
}
#[derive(serde::Deserialize)]
pub struct ApplicationSettings {
pub port: u16,
pub host: String,
} }
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
@ -16,14 +24,55 @@ pub struct DatabaseSettings {
pub fn get_configuration() -> Result<Settings, config::ConfigError> { pub fn get_configuration() -> Result<Settings, config::ConfigError> {
// Initialise configuration reader // Initialise configuration reader
let mut settings = config::Config::default(); let mut settings = config::Config::default();
let base_path = std::env::current_dir().expect("Failed to determine the current directory");
let configuration_directory = base_path.join("configuration");
// Add config from `configuration` file (yaml, json, etc.) // Read default config file
settings.merge(config::File::with_name("configuration"))?; settings.merge(config::File::from(configuration_directory.join("base")).required(true))?;
let environment: Environment = std::env::var("APP_ENVIRONMENT")
.unwrap_or_else(|_| "local".into())
.try_into()
.expect("Failed to parse APP_ENVIRONMENT.");
settings.merge(
config::File::from(configuration_directory.join(environment.as_str())).required(true)
)?;
settings.merge(config::Environment::with_prefix("app").separator("__"))?;
// Try convert into Settings type // Try convert into Settings type
settings.try_into() settings.try_into()
} }
pub enum Environment {
Local,
Production,
}
impl Environment {
pub fn as_str(&self) -> &'static str {
match self {
Environment::Local => "local",
Environment::Production => "production",
}
}
}
impl TryFrom<String> for Environment {
type Error = String;
fn try_from(s: String) -> Result<Self, Self::Error> {
match s.to_lowercase().as_str() {
"local" => Ok(Self::Local),
"production" => Ok(Self::Production),
other => Err(format!(
"{} is nto a supported environment. Use either `local` or `production`.", other
)),
}
}
}
impl DatabaseSettings { impl DatabaseSettings {
pub fn connection_string(&self) -> String { pub fn connection_string(&self) -> String {
format!( format!(

View File

@ -13,12 +13,11 @@ async fn main() -> std::io::Result<()> {
let configuration = get_configuration().expect("Failed to read configuration data."); let configuration = get_configuration().expect("Failed to read configuration data.");
// Configure connection to database for our startup // Configure connection to database for our startup
let connection_pool = PgPool::connect(&configuration.database.connection_string()) let connection_pool = PgPool::connect_lazy(&configuration.database.connection_string())
.await
.expect("Failed to connect to Postgres."); .expect("Failed to connect to Postgres.");
// Take port from settings file // Take port from settings file
let address = format!("127.0.0.1:{}", configuration.application_port); let address = format!("{}:{}", configuration.application.host, configuration.application.port);
let listener = TcpListener::bind(address)?; let listener = TcpListener::bind(address)?;
run(listener, connection_pool)?.await?; run(listener, connection_pool)?.await?;
Ok(()) Ok(())