i’ve made a small and simple RUST RESTful server, Im encountering an issue when trying to curl to the docker image version of the program: curl: (56) Recv failure: Connection reset by peer
, and when trying to surf directly to 127.0.0.0:3000
ill get This site can’t be reached
error.
When trying to the run the server using Cargo run
the program returns the correct
Here is my main.rs file:
use axum::{extract::Query, response::Html, routing::get, Router};
use rand::{thread_rng, Rng};
use serde::Deserialize;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.route("/test", get(handler2));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
// `Deserialize` need be implemented to use with `Query` extractor.
#[derive(Deserialize)]
struct RangeParameters {
start: usize,
end: usize,
}
async fn handler(Query(range): Query<RangeParameters>) -> Html<String> {
// Generate a random number in range parsed from query.
let random_number = thread_rng().gen_range(range.start..range.end);
// Send response in html format.
Html(format!("<h1>Random Number: {}</h1>", random_number))
}
// `Deserialize` needs to be implemented to use with `Query` extractor.
#[derive(Deserialize)]
struct UserParameters {
start: usize,
end: usize,
username: String, // Add a string field
}
async fn handler2(Query(user_detailes): Query<UserParameters>) -> Html<String> {
// Generate a random number in range parsed from query.
//let random_number = thread_rng().gen_range(range.start..range.end);
// Send response in html format.
Html(format!("<h1>User start: {}, User end: {}, Username is???: {}</h1>", user_detailes.start, user_detailes.end,user_detailes.username))
}
My Cargo.toml and Dockerfile :
[package]
name = "rust-image"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.5"
rand = "0.8"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
AND
ARG RUST_VERSION=1.70.0
ARG APP_NAME=rust-image
FROM rust:${RUST_VERSION}-alpine AS build
RUN apk add --no-cache clang lld musl-dev git
WORKDIR /app
COPY src /app/src
COPY Cargo.toml /app
ARG APP_NAME
RUN cargo build --release &&
cp ./target/release/rust-image /bin/server
FROM alpine:3.18 AS final
ARG UID=10001
RUN adduser
--disabled-password
--gecos ""
--home "/nonexistent"
--shell "/sbin/nologin"
--no-create-home
--uid "${UID}"
appuser
USER appuser
COPY --from=build /bin/server /bin/
EXPOSE 3000
CMD ["/bin/server"]
Im using the following command to run the Docker image – docker run -it --rm -p 3000:3000 rust-image1
1