💧

Elixir

Programming Languages & Runtimes

ភាសាសរសេរកម្មវិធីមុខងារសម្រាប់បង្កើតកម្មវិធីដែលអាចធ្វើមាត្រដ្ឋានបាន និងអាចថែទាំបាន

Deployment Info

ការដាក់ពង្រាយ: 2-5 min
ប្រភេទ: Programming Languages & Runtimes
ការគាំទ្រ: 24/7

Share this guide

Overview

Elixir is a dynamic, functional programming language designed for building scalable, maintainable, and fault-tolerant applications. Built on the battle-tested Erlang VM (BEAM), Elixir combines the productivity and expressiveness of modern programming languages with the reliability and concurrency model that has powered telecommunication systems for over 30 years. If you're building web applications, real-time systems, distributed systems, or anything that requires high availability and low latency, Elixir is an excellent choice.

What sets Elixir apart is its incredible concurrency model powered by lightweight processes. You can spawn millions of processes on a single machine, each isolated from others, communicating through message passing. This makes it trivial to write highly concurrent applications without worrying about locks, mutexes, or race conditions. Each process is isolated, so crashes don't cascade - the "let it crash" philosophy means your system self-heals automatically through supervision trees.

Elixir's syntax is clean, Ruby-inspired, and expressive, making it enjoyable to write and easy to read. The language emphasizes immutability and functional programming patterns, leading to code that's easier to reason about and test. Pattern matching is a core feature that makes handling complex data structures elegant and concise. The pipe operator lets you chain function calls in a readable, left-to-right flow that mirrors how you think about data transformations.

The Phoenix Framework is Elixir's killer app for web development. It offers Rails-like productivity with performance that rivals compiled languages - handling millions of WebSocket connections on a single server. Phoenix LiveView lets you build rich, real-time user experiences without writing JavaScript, pushing updates from server to client seamlessly. With built-in support for channels, presence tracking, and pub/sub, Phoenix makes real-time features that are complex in other languages trivially easy.

Elixir's tooling is exceptional. Mix is the built-in build tool that handles everything: creating projects, managing dependencies, running tests, compiling code, and generating documentation. ExUnit provides a robust testing framework with excellent support for concurrent tests and async operations. IEx (Interactive Elixir) offers a powerful REPL for exploring code, debugging, and even hot-swapping code in production systems without downtime.

The OTP (Open Telecom Platform) framework that comes with Erlang provides battle-tested abstractions for building distributed, fault-tolerant systems. GenServers, Supervisors, and Applications give you proven patterns for managing state, handling failures, and structuring applications. This means you're not just getting a language - you're getting decades of expertise in building reliable systems built into the platform.

Elixir excels at building distributed systems. The BEAM VM has built-in support for distributed computing, making it easy to connect multiple nodes and coordinate work across machines. Features like distributed tasks, global process registration, and built-in clustering capabilities mean you can scale horizontally with minimal effort. Combined with libraries like libcluster for automatic cluster formation, Elixir makes distributed computing accessible.

The community is vibrant and welcoming, with excellent documentation, active forums, and thousands of open-source packages via Hex.pm. Major companies like Discord, Pinterest, Moz, and Bleacher Report use Elixir in production, proving its capabilities at scale. Whether you're building a small web app or a massive distributed system, Elixir gives you the tools to build it right.

Key Features

Scalable Concurrency

Lightweight processes and actor model enable millions of concurrent operations with low latency

Fault Tolerance

Supervision trees and 'let it crash' philosophy create self-healing systems that recover from failures

Phoenix Framework

Highly productive web framework with real-time features, LiveView, and performance rivaling compiled languages

Functional Programming

Immutable data, pattern matching, and functional composition for maintainable, bug-resistant code

Distributed Computing

Built-in support for distributed systems with native clustering and inter-node communication

Hot Code Swapping

Update running production systems without downtime or dropping connections

ករណី​ប្រើ

• **Real-Time Web Applications**: Build chat apps, collaborative tools, live dashboards with Phoenix Channels and LiveView
• **API Servers**: High-performance REST and GraphQL APIs handling millions of requests with low latency
• **Distributed Systems**: Microservices, event-driven architectures, and distributed computing with built-in clustering
• **Background Job Processing**: Reliable task queues with Oban for scheduling, retries, and distributed job execution
• **WebSocket Services**: Real-time multiplayer games, live sports updates, financial data streams with millions of concurrent connections
• **IoT & Embedded Systems**: Manage thousands of IoT devices with Nerves for embedded Linux on Raspberry Pi and similar hardware
• **Telecommunication Systems**: Call routing, messaging platforms, and high-availability services (Erlang's original use case)

Installation Guide

**Installation on Ubuntu VPS:**

1. **Install Erlang/OTP:**
```bash
# Add Erlang Solutions repository
wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb
sudo dpkg -i erlang-solutions_2.0_all.deb
sudo apt update

# Install Erlang (OTP 26)
sudo apt install esl-erlang -y

# Verify installation
erl -eval 'erlang:display(erlang:system_info(otp_release)), halt().'
```

2. **Install Elixir:**
```bash
# Install Elixir via apt
sudo apt install elixir -y

# Verify installation
elixir --version
# Should show: Elixir 1.14+ and Erlang/OTP 26

# Install Hex package manager
mix local.hex --force

# Install Phoenix archive (for Phoenix projects)
mix archive.install hex phx_new --force
```

3. **Install PostgreSQL (for database-backed apps):**
```bash
# Install PostgreSQL
sudo apt install postgresql postgresql-contrib -y

# Start PostgreSQL
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Create database user
sudo -u postgres createuser --superuser $USER
sudo -u postgres psql -c "ALTER USER $USER WITH PASSWORD 'yourpassword';"
```

4. **Install Node.js (for Phoenix asset compilation):**
```bash
# Install Node.js 18
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install nodejs -y

# Verify installation
node --version
npm --version
```

5. **Create Your First Phoenix Application:**
```bash
# Create new Phoenix app
mix phx.new myapp --database postgres

# Navigate to project
cd myapp

# Configure database (edit config/dev.exs if needed)
mix ecto.create

# Install dependencies
mix deps.get

# Start Phoenix server
mix phx.server
```

6. **Access Your Application:**
```
Visit: http://localhost:4000
```

7. **Set Up for Production (Systemd Service):**
```bash
# Build release
export MIX_ENV=prod
export SECRET_KEY_BASE=$(mix phx.gen.secret)
export DATABASE_URL=ecto://USER:PASS@localhost/myapp_prod

mix deps.get --only prod
mix compile
mix assets.deploy
mix release

# Create systemd service
sudo nano /etc/systemd/system/myapp.service
```

Add this configuration:
```ini
[Unit]
Description=My Phoenix App
After=network.target

[Service]
Type=simple
User=deploy
Group=deploy
WorkingDirectory=/home/deploy/myapp
Environment="PORT=4000"
Environment="MIX_ENV=prod"
Environment="SECRET_KEY_BASE=your_secret_key"
Environment="DATABASE_URL=ecto://user:pass@localhost/myapp_prod"
ExecStart=/home/deploy/myapp/_build/prod/rel/myapp/bin/myapp start
Restart=on-failure
RestartSec=5
SyslogIdentifier=myapp

[Install]
WantedBy=multi-user.target
```

8. **Start Production Service:**
```bash
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp

# Check status
sudo systemctl status myapp

# View logs
sudo journalctl -u myapp -f
```

9. **Set Up Nginx Reverse Proxy:**
```bash
sudo nano /etc/nginx/sites-available/myapp

# Add this configuration:
server {
listen 80;
server_name yourdomain.com;

location / {
proxy_pass http://localhost:4000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

# Enable site
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

10. **Set Up SSL with Let's Encrypt:**
```bash
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com
```

Configuration Tips

**Essential Configuration:**

1. **Mix Project Configuration (mix.exs):**
```elixir
defmodule MyApp.MixProject do
use Mix.Project

def project do
[
app: :myapp,
version: "0.1.0",
elixir: "~> 1.14",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end

def application do
[
mod: {MyApp.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end

defp deps do
[
{:phoenix, "~> 1.7"},
{:phoenix_live_view, "~> 0.20"},
{:phoenix_ecto, "~> 4.4"},
{:ecto_sql, "~> 3.10"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 3.3"},
{:phoenix_live_reload, "~> 1.4", only: :dev},
{:jason, "~> 1.4"},
{:plug_cowboy, "~> 2.6"}
]
end
end
```

2. **Runtime Configuration (config/runtime.exs):**
```elixir
import Config

if config_env() == :prod do
database_url = System.get_env("DATABASE_URL") ||
raise "DATABASE_URL not available"

config :myapp, MyApp.Repo,
url: database_url,
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
socket_options: [:inet6]

secret_key_base = System.get_env("SECRET_KEY_BASE") ||
raise "SECRET_KEY_BASE not available"

host = System.get_env("PHX_HOST") || "example.com"
port = String.to_integer(System.get_env("PORT") || "4000")

config :myapp, MyAppWeb.Endpoint,
url: [host: host, port: 443, scheme: "https"],
http: [ip: {0, 0, 0, 0, 0, 0, 0, 0}, port: port],
secret_key_base: secret_key_base,
server: true
end
```

3. **Phoenix Endpoint Configuration (lib/myapp_web/endpoint.ex):**
```elixir
defmodule MyAppWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :myapp

# WebSocket configuration
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]]

# Session configuration
plug Plug.Session,
store: :cookie,
key: "_myapp_key",
signing_salt: "random_salt"

plug MyAppWeb.Router
end
```

4. **Database Configuration (Ecto):**
```elixir
# config/dev.exs
config :myapp, MyApp.Repo,
username: "postgres",
password: "postgres",
hostname: "localhost",
database: "myapp_dev",
stacktrace: true,
show_sensitive_data_on_connection_error: true,
pool_size: 10
```

5. **Router Configuration:**
```elixir
defmodule MyAppWeb.Router do
use MyAppWeb, :router

pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {MyAppWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end

pipeline :api do
plug :accepts, ["json"]
end

scope "/", MyAppWeb do
pipe_through :browser

live "/", HomeLive
live "/posts", PostLive.Index
live "/posts/:id", PostLive.Show
end

scope "/api", MyAppWeb do
pipe_through :api

resources "/users", UserController
resources "/posts", PostController
end
end
```

6. **LiveView Example:**
```elixir
defmodule MyAppWeb.CounterLive do
use MyAppWeb, :live_view

def mount(_params, _session, socket) do
{:ok, assign(socket, :count, 0)}
end

def handle_event("inc", _params, socket) do
{:noreply, update(socket, :count, &(&1 + 1))}
end

def handle_event("dec", _params, socket) do
{:noreply, update(socket, :count, &(&1 - 1))}
end

def render(assigns) do
# Template with counter and buttons
end
end
```

7. **GenServer for State Management:**
```elixir
defmodule MyApp.Counter do
use GenServer

# Client API
def start_link(initial_value) do
GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)
end

def increment do
GenServer.call(__MODULE__, :increment)
end

def get_value do
GenServer.call(__MODULE__, :get_value)
end

# Server callbacks
def init(initial_value) do
{:ok, initial_value}
end

def handle_call(:increment, _from, state) do
{:reply, state + 1, state + 1}
end

def handle_call(:get_value, _from, state) do
{:reply, state, state}
end
end
```

8. **Supervision Tree:**
```elixir
defmodule MyApp.Application do
use Application

def start(_type, _args) do
children = [
MyApp.Repo,
MyAppWeb.Endpoint,
{Phoenix.PubSub, name: MyApp.PubSub},
MyApp.Counter # Add your GenServer here
]

opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
```

9. **Testing Configuration:**
```elixir
# test/myapp_web/live/counter_live_test.exs
defmodule MyAppWeb.CounterLiveTest do
use MyAppWeb.ConnCase
import Phoenix.LiveViewTest

test "increments counter", %{conn: conn} do
{:ok, view, _html} = live(conn, "/counter")

assert view |> element("h1") |> render() =~ "Counter: 0"

view |> element("button", "+") |> render_click()

assert view |> element("h1") |> render() =~ "Counter: 1"
end
end
```

10. **Performance & Production Best Practices:**
- Use releases for deployment (not mix phx.server in production)
- Enable connection pooling with proper pool_size
- Configure proper logging levels (info in production, debug in dev)
- Use Ecto's multi for database transactions
- Implement rate limiting with Plug.RateLimiter or Hammer
- Use Phoenix.Tracker for distributed presence
- Enable clustering with libcluster for horizontal scaling
- Monitor with Telemetry and tools like AppSignal or New Relic

វាយតម្លៃអត្ថបទនេះ

-
Loading...

ត្រៀមខ្លួនរួចរាល់ហើយឬនៅដើម្បីដាក់ពង្រាយកម្មវិធីរបស់អ្នក? ?

Get started in minutes with our simple VPS deployment process

មិនតម្រូវឱ្យមានកាតឥណទានសម្រាប់ការចុះឈ្មោះទេ • ដាក់ពង្រាយក្នុងរយៈពេល 2-5 នាទី