Dockerize your FastAPI application that incorporates alembic and sqlachemy. Solve the permission issue between the container and host for the migrations.Dockerize your FastAPI application that incorporates alembic and sqlachemy. Solve the permission issue between the container and host for the migrations.

Solving the FastAPI, Alembic, Docker Problem

2025/12/05 14:26

I was working on a FastAPI application and wanted to dockerize for development, you know the usual, Dockerfile, Docker compose and the lot.

It was meant to be a straightforward process until I ran my alembic migration command and I realized I didn't see the version of the alembic migration in my local directory. The natural solution is to use a bind mount, which once more, should be an easy fix until it wasn't.

I checked out different solutions and I found this one that proposed I use a bind mount but can't simultaneously use the watch process of compose. I'm just too stubborn to accept that solution. I wanted to have my cake and eat it! I wanted my versions in my localhost after it's generated in my container and I also want the "watch" feature from compose. The major problem was permission issues between the host and container.

This write up was my fix and should work for folks using Flask. The brilliant UV (I highly recommend) is used for package dependency management . Django users can check this out. Enough story, let's setup.

Dockerfile

# 1. Use Python 3.13 bookworm as the base FROM ghcr.io/astral-sh/uv:python3.13-bookworm # 2. Set the working directory WORKDIR /app # 3. Set environment variables for UV # UV_COMPILE_BYTECODE: Compiles python files to .pyc for faster startup # UV_LINK_MODE: copy (safer for docker layers than hardlinks) ENV UV_COMPILE_BYTECODE=1 ENV UV_LINK_MODE=copy # 4. create a non-root user for security RUN useradd -u 1000 app # 5. Set HOME explicitly to /app # This prevents the "/nonexistent/.cache/uv" error by telling tools # to look for their config/cache in /app instead of /nonexistent ENV HOME=/app # 6. Ensures the /app directory (and everything inside) is owned by the app user # We run this BEFORE switching users RUN chown -R app:app /app # 7. Copy pyproject.toml and uv.lock with correct ownership # changing ownership during COPY is more efficient than running chown later COPY --chown=app:app pyproject.toml uv.lock ./ # 8. Switch to the non-root user BEFORE installing dependencies USER app # 9. Install dependencies # Since we are now the 'app' user, the .venv will be owned by 'app' # and the cache will be written to /app/.cache/uv. RUN uv sync --frozen --no-install-project --no-dev # 10. Copy the rest of the application code COPY --chown=app:app . . RUN uv sync --frozen --no-dev # 11. Expose the port EXPOSE 8000 # 12. Command to run the application # For production: CMD ["uv", "run", "fastapi", "run", "main.py" ... # This assumes your main.py is in root, I usually have mine in src/main.py # so change it accordingly CMD ["uv", "run", "fastapi", "dev", "main.py", "--host", "0.0.0.0", "--port", "8000"]

I will explain some of my choices here, the comments should suffice for the rest.

In (4.) above, We create a user and assign a UID(user ID) value of 1000, when we create files, it is assigned a UID and GID(group ID), we specifically prefer to use 1000 because many Linux distributions assign that to the first regular user created on a system. Hence, matching 1000 can align container UID with host UID for easier file permission mapping. Feel free to switch things if this is not your use case since you now understand the rationale.

In (5.) above, I am using uv for my package and project management on my host and it just makes sense to continue that. When you install a dependency with uv, it creates a cache of that dependency globally ( i.e in your system directory) especially if you re-install a dependency or use in another project. It stores them usually in $HOME/.cache/uv, by setting this variable to /app, we are making sure it is stored in /app/.cache/uv. If we don't do that, we get /nonexistent/.cache/uv which is either “unwritable” or absent and causes errors. You can also choose not to have a cache and it will reduce you final image size greatly especially for production, but for development, I choose to do that. You can use the UVNOCACHE flag.

Let us also look at (9.) above. Continuing from (5.) above, you could also include the --no-cache flag here.

--frozen: uv.lock ensures consistency installs across environments. --no-install-project: is used to avoid installing the project here for optimal layer caching. By separating this from the install, when the source changes, this does not get rebuilt, the install layer(10) is done again, making your image rebuild even faster. --no-dev: Avoids installing development dependencies.

Lovely! congratulations if you made it through that. It becomes easier from here!

Docker Compose

Let's write the docker-compose.yaml (yes, the docker docs prefer yaml over yml). The aim is to build our fastapi application and have it connected to a postgres database. Let us write it and explain a few things:

services: db: image: postgres env_file: - .env ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql restart: always api: build: . env_file: - .env depends_on: - db ports: - "8000:8000" develop: watch: - path: ./src action: sync target: /app/src - path: ./pyproject.toml action: rebuild working_dir: /app volumes: - ./migrations:/app/migrations:z - ./migrations/versions:/app/migrations/versions:z volumes: postgres_data:

I love my docker compose file looking neat and simple and typically avoid unnecessary variable. For example, I simply usually can not wrap my head around why people choose to use environment and create a long list of environment variables in the yaml file thus excessively lengthening the file. Having a .env file and just specifying it, works a treat. You should follow these best practices for a smooth output.

Pro tip: Just use os.environ to load them in your python file.

Pro tip #2: You can view those variables with docker compose config \n The key part to explain which is largely the reason why I wrote this is the “api.volumes“ section. We create a bind mount separately for the migrations and for versions under migrations. The important bit is in fact the "z" that follows. Without it, we keep getting permission errors. What does it do? In our context, it tells docker to relabel the SELinux security context of the host path so container processes can access it. Thus, I am able to use the bind mount for my migrations and hence, see my versions in my host each time I run a migration command in the container as well as use the watch feature of compose. Finally, we eat out cake and still have it!

PS: For users on macOS or Windows (which are common Docker development environments), this flag may be unnecessary and subsequently be ignored. You can test that out!

.dockerignore

__pycache__/ .venv .ruff_cache ./src/email_templates/ .env

Finally…

I suggest creating a directory for your alembic migration say "migrations" and sub-directory "versions", run your alembic init. Do not forget to change the script_location variable in your alembic.ini as well as edit the appropriate part of your env.py.

docker compose up --watch

In a second terminal,

docker compose exec api uv run alembic revision --autogenerate -m "Initial" docker compose exec api uv run alembic upgrade head

Conclusion

If you completed this, I hope you have learnt a thing or two. A lot of these are my personal opinion and solution so you may find yourself not agreeing with some, that's okay. Feel free to send me a message on LinkedIn. Thanks!!

\

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

SPX Breaks the Mold, TRUMP Hikes 1% – Is MoonBull the Next 100x Crypto Presale Poised for Massive Liftoff?

SPX Breaks the Mold, TRUMP Hikes 1% – Is MoonBull the Next 100x Crypto Presale Poised for Massive Liftoff?

Ever wondered why some crypto coins skyrocket to unbelievable heights while others fizzle out or crash and burn? SPX6900 and Official Trump have grabbed headlines with massive rallies and hype-driven attention, yet their wild swings leave many investors cautious. Is it sheer luck, timing, or something hidden in the tokenomics and community behind these projects? This article compares two high-profile altcoins and one fresh underdog to spot which could be the next 100x crypto presale. Among these projects, MoonBull (MOBU) crypto’s presale stands out for its early-stage entry, structured roadmap, and potential to deliver big gains before launch. MoonBull ($MOBU): The Next 100x Crypto Presale Worth Your Attention MoonBull is built on an Ethereum-based ecosystem, combining meme-style virality with serious tokenomics. The presale is currently in Stage 6, with a token price of $0.00008388. The project’s presale structure is clear and transparent. Each stage raises the token price, creating scarcity and rewarding early adoption. SPX Breaks the Mold, TRUMP Hikes 1% - Is MoonBull the Next 100x Crypto Presale Poised for Massive Liftoff? 4 Staking and passive-income features give MOBU crypto more substance than a pure meme coin. From Stage 10 onward, holders can earn up to 95 percent APY on staked tokens. For a sense of scale, investing just $200 at Stage 6 could net roughly 2.38 million $MOBU tokens, which, at the projected listing price of $0.00616, could be worth over $14,600. That kind of upsid,e combined with real utility, scarcity mechanics, and staking, sets MOBU crypto apart as the next 100x crypto presale that might actually deliver. Powered by Ethereum: Built on the Network That Never Sleeps MoonBull is deployed on the Ethereum blockchain to leverage the most trusted, battle-tested infrastructure in decentralized finance. Using the ERC-20 standard ensures seamless compatibility with major wallets, DEXs, dashboards, and DeFi applications. No bridges, no wrappers, no additional steps, every tool works out of the box. Ethereum’s vast validator network and robust audit ecosystem protect the integrity of MoonBull’s contract functions, including reflections, burns, sell taxes, and staking operations. SPX6900 (SPX) Rises 1.2%: What’s Behind Today’s Price Boost? SPX6900 ($SPX), ranked #78, is trading at $0.7076 after a 1.2% increase over the past 24 hours, reflecting renewed interest and positive market momentum. The token’s market cap has grown to $658.84M, supported by a significant 33.07% surge in 24h trading volume to $21.58M, signaling active trading and fresh liquidity entering the market. With 930.99M SPX circulating out of a 1B max supply and 219.55K holders, SPX benefits from wide distribution and solid community participation. A 3.27% volume-to-market-cap ratio indicates healthy trading relative to its size, contributing to today’s upward price movement and reinforcing short-term bullish sentiment. OFFICIAL TRUMP (TRUMP) Climbs Nearly 1%: What’s Driving Today’s Price Rise? OFFICIAL TRUMP ($TRUMP), ranked #58, is trading at $6.07 after a 0.95% increase over the past 24 hours, showing steady upward momentum. The token’s market cap has risen to $1.21B, accompanied by a strong 30.01% surge in 24h trading volume to $203.67M, highlighting renewed trader interest and active market participation. With 199.99M TRUMP circulating out of a fixed 999.99M total supply and 631.87K holders, investor confidence is reinforced by scarcity and broad adoption. A 16.69% volume-to-market-cap ratio indicates high liquidity relative to its size, contributing to today’s positive price movement and signaling sustained short-term bullish sentiment for TRUMP. SPX Breaks the Mold, TRUMP Hikes 1% - Is MoonBull the Next 100x Crypto Presale Poised for Massive Liftoff? 5 Final Words SPX6900 and Official Trump both offer high volatility and meme-driven swings but carry major downside risks from centralization vulnerabilities and massive losses from previous highs. Meanwhile, MOBU crypto presents a compelling alternative. With a transparent 23-stage presale, tokenomics designed for holders, staking for passive yield, and ultra-low entry price, it looks positioned to deliver where pure meme plays might disappoint. For anyone who missed the last big moonshot, MOBU crypto offers a second chance at the next 100x crypto presale. Consider joining while Stage 6 pricing is in effect. This presale is not to sleep on. SPX Breaks the Mold, TRUMP Hikes 1% - Is MoonBull the Next 100x Crypto Presale Poised for Massive Liftoff? 6 For More Information: Website: Visit the Official MOBU Website  Telegram: Join the MOBU Telegram Channel Twitter: Follow MOBU ON X (Formerly Twitter) Frequently Asked Questions About Next 100x Crypto Presale What is a presale in the context of the next 100x crypto presale? A presale lets investors buy crypto tokens before public listing at a lower price, which may deliver significant gains if the token’s value rises after launch. Why does the MOBU crypto presale have the potential for the next 100x? Because it combines a low entry price, structured price growth per stage, and strong tokenomics, amplifying potential upside if the listing goes well. Can staking in MOBU crypto reduce investment risk? Yes, staking offers up to 95 percent APY, allowing holders to earn passive rewards while waiting for listing. What happens if MOBU crypto fails to list at projected price? As with any presale, there is risk. Returns could be limited or negative if listing price underwhelms or adoption fails. Is liquidity locked for MoonBull (MOBU) once listed? Yes, liquidity is locked for 24 months post-launch to prevent rug pulls or sudden dumps. Glossary of Key Terms Presale: Early sale of tokens before public listing, often at discounted prices Tokenomics: The economic design of a cryptocurrency including supply, distribution, incentives, burns, and staking. Staking: Locking tokens securely to earn rewards. Reflection: A mechanism where a portion of each transaction redistributes tokens to holders. Burn: Permanent removal of tokens from circulation to create scarcity and potential value increase. Liquidity Lock: Mechanism to prevent immediate selling by locking pool funds for a fixed period. ROI (Return on Investment): The percentage gain or loss on funds invested. Max Supply: The total number of tokens that will ever exist for a cryptocurrency. Article Summary This comparative analysis examines SPX6900 and Official Trump against the emerging presale candidate MoonBull (MOBU). The first two rely heavily on meme hype and remain volatile with questionable fundamentals. MOBU crypto offers structured presale pricing, staking rewards, deflationary tokenomics, and strong community incentives, making it a strong contender for the next 100x crypto presale. For those chasing 2025 moonshots, MOBU blends meme energy with real tokenomics designed for growth. Disclaimer This article is for informational purposes only and does not constitute financial or investment advice. Cryptocurrency investments carry significant risk and may result in total loss of invested capital. Always conduct your own research before investing. Read More: SPX Breaks the Mold, TRUMP Hikes 1% – Is MoonBull the Next 100x Crypto Presale Poised for Massive Liftoff?">SPX Breaks the Mold, TRUMP Hikes 1% – Is MoonBull the Next 100x Crypto Presale Poised for Massive Liftoff?
Share
Coinstats2025/12/06 03:15